Recently, a user asked how to add additional fields, such as QQ number or WeChat ID input boxes, to the WordPress user profile editing page.
WordPress does not include these fields by default. To add them, you must use code to create custom fields. While plugins can achieve this, it's often preferable to avoid them. This tutorial demonstrates how to add custom user profile fields using only code, without plugins.
Adding Custom User Fields
First, we will add a 'WeChat ID' field to the profile editing page.
Copy the following code into your theme's functions.php file. This will add a 'WeChat ID' form field to the user profile page.
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;
}
if ( isset( $_POST['wx_username'] ) ) {
update_user_meta( $user_id, 'wx_username', sanitize_text_field( $_POST['wx_username'] ) );
}
}
function wizhi_extra_user_profile_fields( $user ) { ?>
<h3>Additional Profile Information</h3>
<table class='form-table'>
<tr>
<th><label for='wx_username'>WeChat ID</label></th>
<td>
<input type='text' id='wx_username' name='wx_username' size='20' value='<?php echo esc_attr( get_the_author_meta( 'wx_username', $user->ID ) ); ?>'>
<span class='description'>Please enter your WeChat ID.</span>
</td>
</tr>
</table>
<?php }
Code Explanation & Corrections:
- The code uses
wx_usernameas the meta key. The label and description have been updated to 'WeChat ID' for clarity. - The saving function now checks if the
$_POST['wx_username']variable is set and sanitizes the input usingsanitize_text_field()for security. - This code adds the field to both the user's own profile page and the admin's user edit screen.
Retrieving the Custom Field
After adding the field, you can retrieve and display its value. The basic method is shown below:
<?php
$current_user = wp_get_current_user();
$wechat_id = get_user_meta( $current_user->ID, 'wx_username', true );
if ( ! empty( $wechat_id ) ) {
echo 'WeChat ID: ' . esc_html( $wechat_id );
}
?>
Code Explanation:
- The
get_user_meta()function retrieves the user meta data. The third parameter (true) ensures a single string is returned. - The value is escaped with
esc_html()before output for security. - Place this code in any template file (e.g.,
single.php,author.php) where you want to display the field.
Displaying Another User's Field
To display an author's custom field on a post page, use this code:
<?php
$author_id = get_the_author_meta( 'ID' );
$wechat_id = get_user_meta( $author_id, 'wx_username', true );
if ( ! empty( $wechat_id ) ) {
echo 'Author\'s WeChat ID: ' . esc_html( $wechat_id );
}
?>