Add Custom User Fields to the WordPress Profile Screen and Retrieve Them

When building features in WordPress, we often need extra custom fields to support our own logic. User fields are one example of that. There are plenty of plugins that make post custom fields easy to create, but user custom fields are less commonly supported and often less convenient to manage.

Fortunately, adding them directly in code is not difficult.

Add a custom user field in code

The following example adds a custom field called “Weibo username” to the user profile editing screen. If you place the code in a theme’s functions.php file or in plugin code, the field will appear in the profile editor and its value will be stored in the wp_usermeta table.

add_action( 'show_user_profile', 'wizhi_extra_user_profile_fields' );
add_action( 'edit_user_profile', 'wizhi_extra_user_profile_fields' );
add_action( 'personal_options_update', 'wizhi_save_extra_user_profile_fields' );
add_action( 'edit_user_profile_update', 'wizhi_save_extra_user_profile_fields' );

function wizhi_save_extra_user_profile_fields( $user_id ){
if ( !current_user_can( 'edit_user', $user_id ) ) { return false; }
    update_user_meta( $user_id, 'weibo_username', $_POST['weibo_username'] );
}

function wizhi_extra_user_profile_fields( $user ){ ?>
<h3>附加用户字段</h3>

<table class="form-table">
    <tr>
        <th><label for="weibo_username">微博用户名</label></th>
        <td>
            <input type="text" id="weibo_username" name="weibo_username" size="20" value="<?php echo esc_attr( get_the_author_meta( 'weibo_user_name', $user->ID )); ?>">
            <span class="description">请输入微博用户名。</span>
        </td>
    </tr>
</table>
<?php }?>

Retrieve the custom user field

After the field has been added and saved, retrieving it is very easy. WordPress provides the get_user_meta() function for exactly this purpose.

$current_user = wp_get_current_user();
get_user_meta( $current_user->ID, 'weibo_username', true);
  • First use wp_get_current_user() to get the user object.
  • Then use get_user_meta() to fetch the user’s custom field value.

That is all it takes to add and retrieve a simple custom user field in WordPress.

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *