I’ve found these errors in your code:
- The saving proccess of custom user fields is hooked to registration but not to update user profile actions.
- You are using
update_usermeta
, a obsolete function, useupdate_user_meta
instead. - You are using
get_the_author_meta
with$user->ID
without checking before if$user
is an object, which generate errors on new user registration form (also I recommend useget_user_meta
instead). - You are not sanitze/validate the data of company field (I’m not sure what type of data you expect here, propposed
saniteze_text_field
as example).
I’ve made some changes and tested.
function custom_user_profile_fields($user){
$previous_value="";
if( is_object($user) && isset($user->ID) ) {
$previous_value = get_user_meta( $user->ID, 'company', true );
}
?>
<h3>Extra profile information</h3>
<table class="form-table">
<tr>
<th><label for="company">Company Name</label></th>
<td>
<input type="text" class="regular-text" name="company" value="<?php echo esc_attr( $previous_value ); ?>" id="company" /><br />
<span class="description">Where are you?</span>
</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){
if(!current_user_can('manage_options'))
return false;
# save my custom field
if( isset($_POST['company']) ) {
update_user_meta( $user_id, 'company', sanitize_text_field( $_POST['company'] ) );
} else {
//Delete the company field if $_POST['company'] is not set
delete_user_meta( $user_id, 'company', $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' );
Also, this piece of code block any user to save the data if he/she has not “manage_options” capability, which is a capability usually only administrators have, so users won’t can update these fields:
if(!current_user_can('manage_options'))
return false;
So, remove it or make another checking of user capabality if it is needed. For example, checking if current user can edit the user being update seems better:
if ( !current_user_can( 'edit_user', $user_id ) )
return false;