How to add custom fields to WordPress user profile programmatically

In this tutorial, we’ll dive into adding custom fields to user profiles in WordPress. Primarily, we’ll focus on the programmatic approach, ideal for those who prefer hands-on control and coding. We’ll walk through the steps to modify user profiles directly in your theme’s functions.php file or through a custom plugin. Additionally, for those seeking a more straightforward method, we’ll briefly cover how to achieve this using a WordPress plugin.

In the upcoming sections of this article, we will delve into the essential WordPress hooks that enable the integration of custom fields into user profiles. These hooks are crucial as they allow us to insert our custom fields at the right points in the user profile management flow. We’ll also cover the necessary HTML markup to properly render these custom user profile fields in the WordPress admin. We’ll also emphasize the importance of implementing the appropriate authorization checks and validating and sanitizing input data to prevent common security vulnerabilities.

In the end of the article, you will learn how to implement your own fields in WordPress profiles like this:

WordPress add custom field to user profile

Adding the custom field to the user profile

In this example we’ll add a custom field called “Country” using a text input.

To add custom fields to the user profile, we will use the following WordPress hooks:

  • show_user_profile – this hook is fired when a user edits their own user profile page
  • edit_user_profile – this hook is fired when an administrator (or someone with the required capability) edits other users’ profiles

Using these hooks, you can add fields to the user profile with the following code snippet:

add_action( 'show_user_profile', 'my_custom_user_profile_fields' );
add_action( 'edit_user_profile', 'my_custom_user_profile_fields' );

function my_custom_user_profile_fields( $user ) {
  $saved_country = get_user_meta( $user->ID, 'country', true ); ?>
  <h3><?php _e('Additional information'); ?></h3>

  <table class="form-table">
    <tr>
      <th><label for="country"><?php _e('Country'); ?></label></th>
      <td>
        <input type="text" name="country" id="country" value="<?php echo esc_attr($saved_country); ?>" />
      </td>
    </tr>
  </table>
<?php }

Let’s see a breakdown of what this code does:

  1. We use the above-mentioned show_user_profile and edit_user_profile actions to hook into the edit profile page
  2. The my_custom_user_profile_fields() function is called when the show_user_profile or edit_user_profile hooks are triggered. It receives the $user object, which contains data about the current user whose profile is being viewed or edited. The $user object is an instance of WP_User class.
  3. $saved_country = get_user_meta( $user->ID, 'country', true ); fetches the saved ‘country’ user meta data. get_user_meta() is a WordPress function that retrieves metadata from a user’s profile based on the specified key (‘country’) and user ID. We also pass a third argument $single set to true, which returns only the first value it finds for the specified meta key associated with the user. This is useful when you are sure that there’s only one value for the meta key or when you’re only interested in the first value. If $single was set to false, the function would return an array of all values associated with the specified meta key for the user, which could be useful for meta keys that have multiple values.
  4. The function continues with HTML to display the custom ‘Country’ field in the user profile form. While we won’t delve into the specifics of each HTML tag used, it’s important to highlight the usage of esc_attr($saved_country) in the input field. The value of this field is pre-populated with the saved country data (if any) using esc_attr($saved_country). The esc_attr function ensures that the value is safe to output in the HTML attribute by escaping any harmful characters.

At this point you should have a field that looks like this in the user profile:

WordPress display custom field in user profile

However, if you try to update its value, you will see that nothing happens. In the next section we’ll explore how to persist this value in the database.

Gain Valuable Insights From Your WordPress User Data

Saving the profile field values in the database

To save the fields in the database, we can hook into the personal_options_update and edit_user_profile_update WordPress actions:

add_action( 'personal_options_update', 'my_save_user_profile_fields' );
add_action( 'edit_user_profile_update', 'my_save_user_profile_fields' );

function my_save_user_profile_fields( $user_id ) {
  if ( empty( $_POST['_wpnonce'] ) || ! wp_verify_nonce( $_POST['_wpnonce'], 'update-user_' . $user_id ) ) {
    return;
  }

  if ( !current_user_can( 'edit_user', $user_id ) ) {
    return;
  }

  update_user_meta( $user_id, 'country', $_POST['country'] );
}

This code snippet saves the custom field data in WordPress user profiles:

  1. It registers the my_save_user_profile_fields() callback to be called on the following actions:
    • personal_options_update: Triggered when a user updates their own profile.
    • edit_user_profile_update: Triggered when an administrator updates another user’s profile.
  2. Nonce verification: the code checks the nonce field for security. A nonce (number used once) is a unique token used in WordPress to verify that the request to update the profile comes from a legitimate source, preventing CSRF (Cross-Site Request Forgery) attacks.
  3. Permission Check: we use the current_user_can() function to ensure that the current user has the edit_user capability to modify the profile information of the user with the specified $user_id. It’s a security measure to prevent unauthorized profile edits.
  4. We finally call the update_user_meta() function to save the ‘country’ data from the form to the user’s profile. It takes three parameters: the user ID, the meta key (‘country’), and the new value from the submitted form ($_POST['country']). This line updates or adds the ‘country’ user meta field with the value submitted in the form.

With this code snippet applied, if you enter a value into the Country field and update the user profile, the value will be saved and displayed in the input when you open the user profile. With this you have a fully working user profile field. Following the same steps, you can add additional user profile fields as per your requirements.

WordPress save custom user profile field to database

Using a plugin to add custom fields

If you’re looking for a more straightforward solution that doesn’t require custom code, the Users Insights plugin’s Custom Fields feature allows you to add as many fields as you like to the user profile sections. It supports different field types, including text, number, and option fields.

Users Insights create custom fields

Additionally, these custom fields are conveniently displayed and available for editing in the plugin’s dedicated user profile section. This section not only showcases the custom fields but also integrates additional user activity data and information from third-party plugins.

WordPress custom user fields in profile

All custom fields are also available in the Users Insights user table. This means that you can explore multiple fields for all users at once, and additionally, you can sort and search the user list by any of these fields. This includes all user meta fields regardless of how they have been added – you can search fields added via Users Insights, added programmatically (using the method above) or any user meta fields that are added by 3rd party plugins:

Search WordPress user profile fields

To learn more, you can visit the Users Insights Custom Fields page.

Conclusion

Adding custom fields to user profiles in WordPress can significantly enhance user experience and site functionality. Whether you choose the programmatic approach for greater control and customization or opt for a plugin for ease and convenience, both methods can effectively tailor user profiles to your specific needs. We have not only focused on adding these fields but also ensuring they are secure and well-integrated with the rest of your WordPress website.