Please, enter a valid email!
00 days
:
00 hours
:
00 minutes
:
00 seconds

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.

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

  1. Dokumen Saya says:

    ชอบรายการนี้ ครับ
    ตามตั้งแต่ money Chanel ครับ

  2. RandyInvof says:

    Whoa all kinds of superb tips! help on essay thesis writing service how to write a research papers

  3. Averillsul says:

    Find quality shopping articles on Sooper Articles

    How Can we Minimise The unwanted side effects of Plastic on The Environment?Plastic is one of reasons for materials in our society. Plastic has been such a staple of our lives that we can even remember how life was before it became so prevalent. They can be simple studs or they might be something more elaborate with stones and sparkles. countless arose from years of influencing due to which we have learned to idealize a particular body type. This powerful tool has not only changed our life in overall ways, charmingdate But has also affected us at woman / man levels as well. these days, Customers are much more aware while purchasing. Nowadays for some reason trendy. It is simple to set up and adds to the inside of the space. These designs are the right option if you want rooms. It made their lives flat and snug. So snug that nearly the whole lot may be accomplished on line interpersonal, energy, Pay obligations and keep without leaving their homes. The use of standing structures in counseling sessions and daily jobs will significantly support they. These are commonly used by many people all across the globe. This is affordable and practical as well as. for people with disabilities, This product is the best for use. As progressively more people are coming across the convenience of buying online, The eCommerce global marketplace is booming with income. Now this tradition has another dimension to it under the way of social distance. No matter what circumstances are when it Halloween you certainly need a disguise. Among top selling categories like electronics, multimedia systems, taste, and others. We all know about some websites that are so much famous for these materials like amazon, craigs list, and other. incredibly, there are numerous people who prefer plastic cases more than microfiber pouches. the most important thing is the school bags manufacturers in Kolkata who is known for a quality product.

  4. Nelsonxne says:

    Over 50 online dating sites

    If thinking about other believers, You’ve come to the proper dating site. Where Dating Gets Better and Better! Find new contacts close to you and get to know folks personally. in this case, When there is a free moment, They can sit down with a cup of coffee and respond to the messages. quite, We have a diverse range of personalities and interests on the site, Who are all connected by their desire to find a genuine connection with someone really compatible. Here are some factors that you should think about when you would like over 50 dating apps.

    Over 50s are one of the fastest growing demographics in online dating, so with roughly 34. As you age group, You’ll not likely want to search for a new partner in bar or clubs and the office ceases to be a potential dating platform. As our net is pitched at older singles, Our members are generally those dating in their 50s, throughout their 60s, In their 70s and perhaps even beyond! As well as this our customer support team goes to great efforts to ensure your safety online. At EliteSingles we aim to make over 50 dating as smooth and accessible an experience as possible. By actively engaged in our dating site, You’ll find some of the most active databases for singles online. This is what will help you stand out from others on the site, And with luck attract quality, Meaningful internet connections that could turn into something much more. from edinburgh, start messaging and take your online romance to offline, with little hassle.

    Top 5 Best Safest 50 Plus dating sites for Over 50 Singles 2018

    Data protection has the main ageda! characteristics: Quick investigate, highly developed Search, Cougar adult dating Advice, let’s Meet, First Date beliefs, Search information Free, Online doctor, experienced, digital, Wink. with regard to those lost hope already, There are over 70 internet dating sites like Over70DatingSite. going on the internet for over 50 dating: Is it on your behalf? Join EliteSingles today and start your search for someone special. if you are a sugar daddy looking for sugar baby or sugar baby seeking sugar daddy, MillionaireMatch shouldn’t suit for you. Many of our members have already established a large circle of friends and log in daily to chat and to speak about God and the world.

    take a deep breath, And before you give up or raise your white flag in defeat, Remember there are numerous features dating communities that cater to the 50 and over crowd. If you are ready about looking for connection with others who are single and over 50, Then a great site for you to choose is SilverSingles. How Many Apps do you want to Sign Up for and Use? Dating over 50 isn’t getting simpler than with EliteSingles. remember the fact that, While Match isn’t majority a senior dating site, There are many older people among its massive user base, So have a shot. most people are love to travel, You can travel with him or her. because of that, We’re able to match people whose individualities and lifestyles complement each other to create over 2500 happy couples every month across all of our platforms.

    Free uniform dating Over 50 site. How to meet over 50 singles

    By visiting our website manage to gain to find other serious singles so you can meet new friends, Find romance or simply meet up online with others sharing similar interests and hobbies as you! Barbara Waxman is hosting her next Odyssey 1 course on October 8 in. This site helps to connect like minded can provide homeowners the same interests and values. With countless thoughts both short and open ended Match. choices: Quick research, higher Search, Over 70 getting to know Advice, on the next paragraphs Meet, more mature Blogs, First Date opinions, Search users Free, electronic mail, Wink. created, of course, Some have found a wife or husband from them, They are certainly more casual than sites that cater to an older crowd. Although the main focus of these dating services is to find love, You will find many people who simply want someone that they can talk to and fill a void. If you want to find an older woman younger man spouse and older man younger woman special connection, It’s a good solution.

    might completed, you’ll be ready meeting potential partners suited to you. How to select the best Over 50 Dating Apps? But rather than just having this info displayed on your profile page, they choose it to hand pick three to seven matches per day. We know your faith and values are important to you. It is not easy feeling like a fish out of water encompassed with blissfully in love couples, So come on our website and turn one of them! Considering divorce is a common experience for over fifty percent who wed, you certainly charmdate.com aren’t alone in your newfound singlehood. But whether divorce or widowhood has thrown a wrench in that particular reverie, Or you just have never found your significant other, Many fifty somethings do feel the single and sometimes a little worried about it. demonstrated Members: 3,200,000 + verified members com is an age gap dating site for older women dating younger men or older men dating younger women.

    and also dating, We also offer you the opportunity to find new friends or people with the same interests. We won’t share your data with 3rd parties. Our supportive dating service and membership base of alluring older singles make us a great place to. verified Members: 3,000,000 + demonstrated members. One of the perks of the website is the present selection subscribers. you are allowed to connect with them with your easy to create singles profile. When new individuals join our site, They take our insightful style test, Letting us get a clear picture of their hopes, cravings, And ideal wife or husband.

    Single as well as over 50? We make dating less difficult

    on the lookout for friends, Casual getting to know, Serious love affairs or just someone to go to the movies with? SilverSingles is a supportive dating site Dating is easier when you have a tool on hand to help you meet interesting singles, And SilverSingles is the ideal tool for the job. there’s a lot of senior dating websites that also offer dating apps. How Many Singles Over 50 are using App? easily find and contact local singles from your community, Or area, And worldwide. While dating nowadays might be varies greatly to when you were in your 20s and 30s our over 50 dating platform makes the whole process accessible, Convenient and additionally it is fun. Elite Singles Even if your son or daughter or grandchildren! You deserve to find someone who understands you and how it is like to date in your 50s.

    Advice for Dating in your 50s

    Want to improve your single status? for that matter, during 2018, Being single and over 50 is the start of a whole new adventure. Best foot forward a big benefit of dating online is that you can go at your own pace. The loss of a loved one or divorce can leave you single and looking for friendship. find out how to rediscover your passion and purpose with these five guidelines. Barbara Waxman is hosting her next Odyssey 1 handyroom on October 8 in. For infinite use, We offer you a Premium Membership with more features and more advantages so sou’ll have even more success. Our online dating platform connects people! to avoid this headache, get started doing these sites and apps for your prime years of feeling those insatiable butterflies: Zoosk exceeding 35 million members, your chances of scoring at least a date or three or five is stellar on Zoosk.

  5. RalphSig says:

    genaric cialis with dapoxetine cialis pills

  6. DavidHooNS says:

    Seo-runs сервис по продвижению сайтов. Огромный опыт работы по выводу сайтво в топ, собственные технологии, доступны кейсы https://xn—–7kcahliahtcp1cinbpc3awc.xn--p1ai/

  7. best free online dating sites with no fees

  8. Google says:

    Google

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

  9. Google says:

    Google

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

  10. 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.

  11. 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.

  12. 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

  13. Lord A. says:

    Thank you! This was helpful 🙂

  14. Nazar Pelekh says:

    Social fields don’t work

  15. dmykos says:

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

  16. Elder Carvalho says:

    Thank you!

Leave a Reply

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