Add Custom Fields to User Profile in WordPress

One of the reasons WordPress is so popular among users is that it provides us with a great user management system and ability to create multi-author blogs and publication platforms. However in some cases there is a necessity to expand the default user information, and add more fields to the user profile. In this tutorial WordPress add meta box to user profile. There are two ways to add user metadata, let's take a closer look at each of them.



Using user_contactmethods filter

The first way is the easiest one, but it has some limitations. By using this method you would able to add contact information, such as social media links, but you won't be able to add any other custom data. In most cases, however, that would be more than enough, that's why we'll show you how to use this first.

user_contactmethods is a filter which is called by wp_get_user_contact_methods. Using this filter we can add required social fields and output them on the user page in the admin panel. Then we would be able to fill out each field, and save the new user information. If you'd like to use this filter, add the following code to your functions.php file:

The function tm_additional_contact_methods is called every time when we're pulling the user information from the database. The argument $fields is an array which contains all the contact options. In our function we use it to add three additional fields, and return it for further processing. After we added the filter, you can find the new fields in the 'Contact Info' section.

WordPress add meta box to user profile

In order to display the saved data on the front-end, use the function get_the_author_meta, for example if you'd like to display the FaceBook profile link, use


get_the_author_meta( ‘facebook’ );

Using 'edit_user_profile' and 'show_user_profile' hooks

The second way of adding user information would be more flexible, but also more complex. It includes two stages, first we need to output the custom fields, and then save their values to the database.

In order to add our own fields, we'd be using edit_user_profile and show_user_profile hooks, which are called right before outputting the 'Update' button on the user page (or on your own profile page). Let's try adding a field for showing user's birthday. In order to do that, we need to add the following code to the functions.php file:


/**
 * Add new fields above 'Update' button.
 *
 * @param WP_User $user User object.
 */
function tm_additional_profile_fields( $user ) {

    $months 	= array( 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' );
    $default	= array( 'day' => 1, 'month' => 'Jnuary', 'year' => 1950, );
    $birth_date = wp_parse_args( get_the_author_meta( 'birth_date', $user->ID ), $default );

    ?>
    <h3>Extra profile information</h3>

    <table class="form-table">
   	 <tr>
   		 <th><label for="birth-date-day">Birth date</label></th>
   		 <td>
   			 <select id="birth-date-day" name="birth_date[day]"><?php
   				 for ( $i = 1; $i <= 31; $i++ ) {
   					 printf( '<option value="%1$s" %2$s>%1$s</option>', $i, selected( $birth_date['day'], $i, false ) );
   				 }
   			 ?></select>
   			 <select id="birth-date-month" name="birth_date[month]"><?php
   				 foreach ( $months as $month ) {
   					 printf( '<option value="%1$s" %2$s>%1$s</option>', $month, selected( $birth_date['month'], $month, false ) );
   				 }
   			 ?></select>
   			 <select id="birth-date-year" name="birth_date[year]"><?php
   				 for ( $i = 1950; $i <= 2015; $i++ ) {
   					 printf( '<option value="%1$s" %2$s>%1$s</option>', $i, selected( $birth_date['year'], $i, false ) );
   				 }
   			 ?></select>
   		 </td>
   	 </tr>
    </table>
    <?php
}

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

Let's examine this code in detail. First, we need to do some preparation work. Since the range of the requested data is limited by the number of days and months, it would be much better to add not simply text input fields, but select boxes with a list of days and months. That's why let's create an array with a list of available months.


$months = array( 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' );

We can also get the value of birth date saved in the database. In order to avoid errors, let's combine the array from the database and the array with default values by using wp_parse_args.


$default = array( 'day' => 1, 'month' => 'January', 'year' => 1950, );
$birth_date = wp_parse_args( get_the_author_meta( 'birth_date', $user->ID ), $default );

The next step would be to write the HTML code for our fields. We're going to fill in the select boxes with for and foreach loops, and check which of the options is saved in the database by using selected function. We should pay a special attention to the name attribute of the select boxes, their value is set in birth_date[day] format. In such a way we can store the date of birth in a single array.

After adding this piece of code we can see the following picture on the user profile page:

User's birth date meta data in WordPress admin panel

Now let's add a mechanism of saving the field values into the database. In order to do that we're going to add the following piece of code in our functions.php:


/**
 * Save additional profile fields.
 *
 * @param  int $user_id Current user ID.
 */
function tm_save_profile_fields( $user_id ) {

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

    if ( empty( $_POST['birth_date'] ) ) {
   	 return false;
    }

    update_usermeta( $user_id, 'birth_date', $_POST['birth_date'] );
}

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

At the beginning of this function we've added several security checks in order to avoid mistakes when saving data to the database.

Now by using get_the_author_meta function we can output the user's date of birth on front-end. In our case this function returns an array with elements containing day, month, and year of birth of the user.

At the end we can combine the first and second examples and use them as a foundation for a function that would display an extended information about the user:


function tm_author_bio() {

    $socials = array(
   	 'twitter' => array(
   		 'label' => 'Twitter',
   		 'url'   => 'https://twitter.com/'
   	 ),
   	 'facebook' => array(
   		 'label' => 'Facebook',
   		 'url'   => 'https://www.facebook.com/'
   	 ),
   
    );

    $birth_date = get_the_author_meta( 'birth_date' );

    ?>
    <div class="author-profile">
   	 <?php echo get_avatar( get_the_author_meta( 'user_email' ), '100' ); ?>
   	 <h5 class="author-profile__name"><?php the_author_posts_link(); ?></h5>
   	 <?php if ( $birth_date ) { ?>
   	 <h6 class="author-profile__meta">
   		 Birth date: <?php  echo implode( ' ', $birth_date ); ?>
   	 </h6>
   	 <?php } ?>
   	 <div class="author-profile__description">
   		 <?php the_author_meta( 'description' ); ?>
   	 </div>
   	 <div class="author-socials">
   	 <?php
   		 foreach ( $socials as $net => $data ) {
   			 if ( get_the_author_meta( $net ) ) {
   				 $url   = esc_url( $data['url'] . esc_attr( get_the_author_meta( $net ) ) );
   				 $label = $data['label'];
   				 echo '<div class="author-socials__item"><a href="' . $url . '" class="author-socials__link">' . $label . '</a></div>';
   			 }
   		 }
   	 ?>
   	 </div>
    </div><?php
}

Let's quickly go through the code in our function. At the beginning we're creating an array with the social media networks data, so that we can use it to display the list of social links of a user. The date of birth can be displayed using implode function, which will transform the elements of the array into a string, using a space as a delimiter. The rest of the user data can be displayed using the standard WP functions such as get_avatar, the_author_posts_link, and the_author_meta.
Feel free to download the source code for this tutorial, which we decided to transform into a small plugin. After installing and activating the plugin, you can display a box with additional user information using this line of code:


do_action( 'tm_author_bio' );

We hope this tutorial helped you understand the methods of adding user metadata to your WordPress site at a deeper level, and implement such methods on your own.

Stay tuned, more tutorials are coming soon!


Don’t miss out these all-time favourites

  1. The best hosting for a WordPress website. Tap our link to get the best price on the market with 30% off. If Bluehost didn’t impress you check out other alternatives.
  2. Website Installation service - to get your template up and running within just 6 hours without hassle. No minute is wasted and the work is going.
  3. ONE Membership - to download unlimited number of WordPress themes, plugins, ppt and other products within one license. Since bigger is always better.
  4. Ready-to-Use Website service is the ultimate solution that includes full template installation & configuration, content integration, implementation of must-have plugins, security features and Extended on-page SEO optimization. A team of developers will do all the work for you.
  5. Must-Have WordPress Plugins - to get the most essential plugins for your website in one bundle. All plugins will be installed, activated and checked for proper functioning. 
  6. Finest Stock Images for Websites - to create amazing visuals. You’ll get access to Depositphotos.com to choose 15 images with unlimited topic and size selection.
  7. SSL Certificate Creation service - to get the absolute trust of your website visitors. Comodo Certificate is the most reliable https protocol that ensures users data safety against cyber attacks. 
  8. Website speed optimization service - to increase UX of your site and get a better Google PageSpeed score.


Andrew Shevchenko

Wonder how WP Customizer works? Learn how to add WP custom fields with Andrew. LinkedIn

Get more to your email

Subscribe to our newsletter and access exclusive content and offers available only to MonsterPost subscribers.

From was successfully send!
Server error. Please, try again later.

13 responses to “Add Custom Fields to User Profile in WordPress”

  1. Google says:

    Google

    The time to read or go to the subject material or web-sites we’ve linked to below.

  2. Google says:

    Google

    Here is a good Blog You might Discover Interesting that we encourage you to visit.

  3. There’s a bug in your code that will prevent you from erasing a user’s birth date. On line 12 of one of your code samples, you check using empty().

    if ( empty( $_POST[‘birth_date’] ) ) {

    This will return true if the user cleared the value of the text box to erase and save the birth date. You should use isset() here. Also, I like to check with empty() afterwards and call delete_user_meta() instead of update to remove the row entirely from the usermeta table rather than keep a row with an empty string value.

  4. Ken says:

    Would it not be better to use a date picker to enter the date, and then to store the date as a UNIX timestamp? Then the date can be processed using the built-in date and time functions.

  5. Cato says:

    Can’t see the code bro :/ seems like there’s something screwed in the page.

    • Alexander says:

      Hi!

      It’s all there. A screenshot would be appropriate, so I could see what you are seeing.

      • Seher Khan says:

        Same. There’s no code in the “Using user_contactmethods filter” functions.php section. Also can’t attach screenshots here

  6. Lord A. says:

    Thank you! This was helpful 🙂

  7. Nazar Pelekh says:

    Social fields don’t work

  8. dmykos says:

    I do not see code: “we need to add the following code to the functions.php file:” Please fix this.

  9. Elder Carvalho says:

    Thank you!

Leave a Reply

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