Site icon YourBlogCoach

How to Add Custom Fields to User Profile in WordPress?

How to Add Custom Fields to User Profiles in WordPress?

Hello guys, In this tutorial, you will learn how to add custom fields to a WordPress user profile in the wp-admin area.

With a custom field, you can add additional info to users and show where you want to show on the frontend side or anywhere.

I would recommend using the child theme’s functions.php file. If you don’t have one, you can see my full detailed guide tutorial on how to create a child theme in WordPress?

Let’s get started.

Add Custom Fields to User Profile

To add custom fields to wordpress user profile, we will use the show_user_profile and edit_user_profile action hooks to render the custom fields.

[php]
<?php
add_action( ‘show_user_profile’, ‘medical_information_users_fields’ );
add_action( ‘edit_user_profile’, ‘medical_information_users_fields’ );

function medical_information_users_fields( $user ) {

// get custom field values
$blood_group = get_user_meta( $user->ID, ‘blood_group’, true );

?>
<h3>Medical Information</h3>

Save Custom Fields Value

Now we will use the personal_options_update and edit_user_profile_update action hooks to save the values of the custom fields in database.

[php]
add_action( ‘personal_options_update’, ‘save_medical_information_users_fields’ );
add_action( ‘edit_user_profile_update’, ‘save_medical_information_users_fields’ );

function save_medical_information_users_fields( $user_id ) {

if( !isset( $_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, ‘blood_group’, $_POST[ ‘blood_group’ ] );

}
[/php]

In the above code, first, we checked whether the nonce is set or not to protect the request URL from malicious. Then we checked whether the current user has permission to edit the user or not.

And finally, we update the user data of that custom field (built in the first step) using the update_user_meta() function. You can also validate fields before updating them.

If you have any queries please let me know in the comment section, and I will respond to you as soon as possible.