I want to save the custom field values in the wp-users table. Do I have to create the fields(client and user_groups) in the table or it gets created automatically when the data gets saved into the database?
Here is my code
function custom_user_profile_fields($user){
global $wpdb;
if(current_user_can('editor')){
if(is_object($user) && isset($user->ID)){
$client = get_user_meta( $user->ID, 'client', true );
$user_groups = get_user_meta( $user->ID, 'user_groups', true );
}else{
$client = null;
$user_groups = null;
}
?>
<table class="form-table">
<tr>
<th><label for="company">Client Name</label></th>
<td>
<input type="text" class="regular-text" name="client" value="<?php echo $client; ?>" id="client" /><br />
</td>
</tr>
<tr>
<th><label for="company">User groups</label></th>
<td><?php
$sql = $wpdb->get_results("SELECT usergroup_name FROM `wp_usergroup`");
?>
<select name="user_groups">
<option>None</option>
<?php
foreach($sql as $sl) { ?>
<option value="<?php echo $sl->usergroup_name;?>"><?php echo ucfirst($sl->usergroup_name); ?></option>
<?php
}
?>
</select></td>
</tr>
</table>
<?php
}
}
add_action( 'show_user_profile', 'custom_user_profile_fields' );
add_action( 'edit_user_profile', 'custom_user_profile_fields' );
add_action( "user_new_form", "custom_user_profile_fields" );
function save_custom_user_profile_fields($user_id){
# again do this only if you can
if(!current_user_can('manage_options'))
return false;
# save my custom field
if( isset($_POST['client']) ) {
update_user_meta( $user_id, 'client', sanitize_text_field( $_POST['client'] ) );
} else {
//Delete the company field if $_POST['company'] is not set
delete_user_meta( $user_id, 'client', $meta_value );
}
if( isset($_POST['user_groups']) ) {
update_user_meta( $user_id, 'user_groups', sanitize_text_field( $_POST['user_groups'] ) );
} else {
//Delete the company field if $_POST['company'] is not set
delete_user_meta( $user_id, 'user_groups', $meta_value );
}
}
add_action('user_register', 'save_custom_user_profile_fields');
add_action( 'personal_options_update', 'save_custom_user_profile_fields' );
add_action( 'edit_user_profile_update', 'save_custom_user_profile_fields' );
Thanks in advance for help