Create Your Own WordPress User Contact Fields

Create Your Own WordPress User Contact Fields

Today I created a new plugin for you. A plugin that deals with users contact methods. Basically when you edit a user in the administration, there’s a “contact information” block. Well, I’d like to show you how to add your own fields there, and to go a bit further, how to show (or not) these new fields on the registration page.

Here is a preview of what we’re going to create:

edit-custom-fields

New user fields on edit page

custom-fields

Custom fields on registration page

And to do so, as usual, we’re going to create a nice and simple plugin!

Step 1: Create The Plugin

Create a new folder in wp-content/plugins and call it “custom-user-contact-methods”. Inside this newly created folder, create a file called “rc-custom-user-contact-methods.php”, and open it in your favorite editor software.

Place this content in your empty file. This code simply registers the plugin:

<?php
/*
Plugin Name: Custom User Contact Methods
Plugin URL: http://remicorson.com/
Description: Add custom fields to users "contact" section
Version: 1.0
Author: Remi Corson
Author URI: http://remicorson.com
Contributors: corsonr
*/

Step 2: Define Your Custom Fields

Next, we need to create a variable that will contain our custom fields, the ones to use in the user edition page, and also on the registration default page. Let’s store these fields into a variable called $extra_fields.

$extra_fields =  array( 
					array( 'facebook', __('Facebook Username', 'rc_cucm'), true ),
					array( 'twitter', __('Twitter Username', 'rc_cucm'), true ),
					array( 'googleplus', __('Google+ ID', 'rc_cucm'), true ),
					array( 'linkedin', __('Linked In ID', 'rc_cucm'), false ),
					array( 'pinterest', __('Pinterest Username', 'rc_cucm'), false ),
					array( 'wordpress', __('WordPress.org Username', 'rc_cucm'), false ),
					array( 'phone', __('Phone Number', 'rc_cucm'), true )
					);

We are storing every field within an array that have 3 parameters, the first one is the field ID, the second one is the field label, and the last one is a boolean information that defines if the field is shown on the registration page or not. You can add as many parameters as you want, for example a placeholder or a required information.

Step 3: Hook The Right Filter

We now need to hook a function to the right filter. In our specific case, the filter is “user_contactmethods”, and the name of the function we are going to create is “rc_add_user_contactmethods”.

// Use the user_contactmethods to add new fields
add_filter( 'user_contactmethods', 'rc_add_user_contactmethods' );

Step 4: Create Our Custom Fields

We now need to create the “rc_add_user_contactmethods” function. It’s the one that will add our custom fields to the user edit page. The good news, is that we stored our fields within an array, it means that the following function will be fully dynamic, and it will be pretty easy to add new fields just by modifying the $extra_fields variable.

/**
 * Add custom users custom contact methods
 *
 * @access      public
 * @since       1.0 
 * @return      void
*/
function rc_add_user_contactmethods( $user_contactmethods ) {

	// Get fields
	global $extra_fields;
	
	// Display each fields
	foreach( $extra_fields as $field ) {
		if ( !isset( $contactmethods[ $field[0] ] ) )
    		$user_contactmethods[ $field[0] ] = $field[1];
	}

    // Returns the contact methods
    return $user_contactmethods;
}

At this step, if you save, and activate the plugin, you should see your custom fields in the user edit page. As we are using the correct hook, we don’t have to create a “save” fields data. So, the plugin is working great for the moment. But i’d like to go a bit further and add the option to display those fields on the registration page. Make sur you check under settings the “Anyone can register” checkbox, otherwise you won’t be able to see the “Register” link.

Step 5: Registration Page Hooks

To add our fields on the registration page, we need to access at least two hooks, and create two functions. One to display the fields, and the second one to save the fields data into the database.

Let’s hook our functions:

// Add our fields to the registration process
add_action( 'register_form', 'rc_register_form_display_extra_fields' );
add_action( 'user_register', 'rc_user_register_save_extra_fields', 100 );

Step 6: Display Custom Fields Registration Page

In the code above we declared two functions. The first one is to display the fields on the registration page. In this part we need to take care of the third parameter of each array in $extra_fields. This boolean parameter tells if the fields has to be shown or not. True: the field is shown, false: the field isn’t shown.

/**
 * Show custom fields on registration page
 *
 * Show custom fields on registration if field third parameter is set to true
 *
 * @access      public
 * @since       1.0 
 * @return      void
*/
function rc_register_form_display_extra_fields() {
    
    // Get fields
    global $extra_fields;

    // Display each field if 3th parameter set to "true"
    foreach( $extra_fields as $field ) {
    	if( $field[2] == true ) { 
    	if( isset( $_POST[ $field[0] ] ) ) { $field_value = $_POST[ $field[0] ]; } else { $field_value = ''; }
    	?>
	    <p>
            <label for="<?php echo $field[0]; ?>"><?php echo $field[1]; ?><br />
            <input type="text" name="<?php echo $field[0]; ?>" id="<?php echo $field[0]; ?>" class="input" value="<?php echo $field_value; ?>" size="20" /></label>
            </label>
	    </p>
	    <?php
    	} // endif
    } // end foreach
}

Step 7: Store Fields Values Upon Registration Process

Now that our fields are shown on the registration page, we need, to store their values into the database. This is the aime of the “rc_user_register_save_extra_fields” function. To do so, we need to use the “wp_update_user()” function.

/**
 * Save field values
 *
 * @access      public
 * @since       1.0 
 * @return      void
*/
function rc_user_register_save_extra_fields( $user_id, $password = '', $meta = array() )  {

	// Get fields
    global $extra_fields;
    
    $userdata       = array();
    $userdata['ID'] = $user_id;
    
    // Save each field
    foreach( $extra_fields as $field ) {
    	if( $field[2] == true ) { 
	    	$userdata[ $field[0] ] = $_POST[ $field[0] ];
	    } // endif
	} // end foreach

    $new_user_id = wp_update_user( $userdata );
}

Conclusion

Well, we saw the basics of how to add new fields to the user contact methods, but that’s all. You can for example remove existing fields such as “Yahoo IM”, “AIM” and “Jabber” doing a simple unset(). But you can also add some functions to sanitize your custom fields in order to check for example if the phone number has an appropriate format, if a field is required or not etc etc… Do not hesitate to ask for specific features in the comments!

Download the plugin

Oh, and a last thing… if you want to display the data of any of your field, simply use this:

// Param 1 is user ID
// Param 2 is field ID
// Param 3 is there to get a var or an array
echo get_user_meta( 1, 'twitter', true );  
Remi
Remi is an expert WordPress developer that coded many great free and premium themes and plugins. His experience on WordPress allows him to produce great stuff and to propose advanced tutorials. (remicorson.com)
Remi
This article has 43 comments
  1. Rudd says:

    Awesome tutorial. I’ve seen some people wrote about adding custom fields in users profile, but none of them show how to hook them in the registration form.

    By showing the custom fields in the registration form, does that mean all of them are “required” fields? Is there any way to make only few of them as “required” fields, and the others just “option” fields?

  2. bucurblog says:

    I like your tutorials explain,a very good job.Thanks Remi.Greetings from Romania…

  3. gestroud says:

    DEFINITELY looking forward to implementing this! It should be part of the core.

  4. Mathew Porter says:

    Great and useful tutorial as ever, need to find some time to get this implemented on a clients site who uses WP Ecommerce

  5. Arnold Babasa says:

    Thank you so much! This has saved me a lot. I have been scratching my head for hours! Well done sir!!

  6. Tom Finger says:

    Hi & thank you a lot! Finally some code that works with my other plugins!
    Is there a way to get the custom fields on top of the form?
    Best regards
    Tom

    1. AJ Clarke | WPExplorer says:

      Of the registration form or the back end form? I’m actually not quite sure for either maybe adding “,1″ into the add_action() function would do it?

      add_action( ‘register_form’, ‘rc_register_form_display_extra_fields’, 1 );

      Admin
  7. Sacha says:

    Hi,

    excellent and clean tutorial.

    One question: how do you make a field required?

    Thanks in advance.

    Sacha

  8. alexander flinch says:

    You are really a great master. The way of your explanation is very excellent.
    Thanks a lot.

  9. am3n says:

    Thank your Remi,
    I’ll try to use this tutorial plugin, but I have question?
    how do I put field description like this

    Field ID: phone_number
    Field Label: Phone Number
    Field Description: Please enter your phone number in following format +[CountryCode]-[AreaCode]-[PhoneNumber] i.e: +62-21-75901234

    1. AJ Clarke | WPExplorer says:

      If you want a field description you could just do a br and add it within the label, no?

      Admin
      1. am3n says:

        thanks for your response, and sorry for late reply.
        If I add br with more description within the label then it’ll be long description.
        anyway, I think I found what I need. It’s a tooltip. can be placed as p title, so all I need adding 4th parameter

  10. seidu says:

    Awesome, many thanks.
    After sleepless nights, you are a life saver. THANKS!!! :)

  11. Fuad Fauzi says:

    Thank God, you are a life saver..

    Next try is editing the fields and making a “required” function.. Thanks to all who contribute in this thread :)

  12. Praveen says:

    Hi Remi

    While Declaring the Custom fields in the array , what is the requirement for having ‘rc_cucm’ along with the Label field , what is the purpose of ‘rc_cucm’ ?

    $extra_fields = array(array(‘facebook’, __( ‘Facebook Username’, ‘rc_cucm’), true ),
    array( ‘twitter’, __( ‘Twitter Username’, ‘rc_cucm’), true ));

  13. selectiveform says:

    I was been trying to create a frontend edit page for user. Any help from you here. Thanks

  14. Curtis says:

    Thanks Remi!!! Found via google search. Love the fact that you give the plugin to anyone, and also show them step by step how it was developed (one of the “clearest” tutorials I have seen for sure!) allowing your viewers to educate ourselves along the way.

  15. rcneil.com says:

    Awesome Tutorial! Incredibly easy to follow, excellent at explaining. Thanks!

  16. Martin Pultz says:

    Thank you, that is an awesome tutorial. I’ve spent hours first playing with different plugins which bloated my site, and then on the WordPress Codex. This is was a great, concise learning experience. Thanks!

  17. Martin Pultz says:

    I wanted to add first and last name to the registration form, which I did using your plugin, but now I have two first names and two last names, as wordpress has these fields just doesn’t offer them during registration. How would I overwrite the original or override it?

  18. Martin Pultz says:

    I noticed duplicate fields showing up on the User Edit page if you added wp default user fields to your registration page. To prevent this from happening:

    Name the fields the same as the wp_usermeta so in the case of first and last name: first_name and last_name

    $extra_fields =  array( 
    					array( 'first_name', __('First Name', 'rc_cucm'), true ),
    					array( 'last_name', __('Last Name', 'rc_cucm'), true )
    )
    
    and Loop over them in rc_add_user_contactmethods().
    
    function rc_add_user_contactmethods( $user_contactmethods ) {
    
        // Get fields
        global $extra_fields;
    
        // Display each fields
        foreach( $extra_fields as $field ) {
    
            // Skip over wp default fields
        	if( $field[0] == "first_name" || $field[0] == "last_name" ) 
                    continue;
    
    	if ( !isset( $contactmethods[ $field[0] ] ) )
        		$user_contactmethods[ $field[0] ] = $field[1];
    	}
    
        // Returns the contact methods
        return $user_contactmethods;
    }
    

    I’ll make a slightly more robust version later that has an array of wp default usermeta that is checked, but this is the gist.

    Hope this is helpful to someone
    Cheers

  19. Vasik says:

    Is it possible to add checkboxes / dropdowns this way, or does that need to be hardcoded?

    1. AJ Clarke says:

      It is possible, in this post example the author uses an input field, but it can be a checkbox or dropdown, you just have to alter the code.

      Admin
  20. Brčina Josip says:

    Awesome tutorial!
    I am not that experienced wordpress programmer but i would like to write plugin that will make new role let’s call it developer, and i would like that all users who register under that role have only custom fields without any standard wordpress fields. Is it possible to add custom fields (and delete old ones from wordpress) but they should be dispayed only for users under certain role, in this case “developer role”. They would have capabilities same as subscriber so they can only go and manage their own profile in dashboard, and that profile page should have only my custom fields. Any help please?

    Thank you alot in advance!

  21. ardge says:

    great plugin although ido have a question is there a possible solution to adding social icons next to the new contact fields? if so could you please specify on the string i must add and where

    thanks

    1. AJ Clarke says:

      It would be possible, on step 6 “Step 6: Display Custom Fields Registration Page” you’ll simply add an img tag before your label inside the paragraph. Something like this…

      <img src="<?php get_template_directory_uri(); ?>/images/<?php echo $field[0]; ?>.png" alt="" />
      

      Then of course add the icons in your theme’s images folder (or alter the code to link elsewhere) and make sure that your icon names are in the same format (twitter.png, facebook.png..etc).

      Admin
  22. Jessica says:

    How would you set it to open the link in a new window? Is that a parameter that can be changed?

    1. AJ Clarke says:

      Not quite sure what you mean. If you are displaying the social links somewhere on your site just at target=”_blank” to the link tag.

      Admin
  23. Brandon Rhodes says:

    How do I provide users a way to update this information *from the front end* once they’ve registered? I’m using WooCommerce and would like to keep customers in the front end at all times.

    1. AJ Clarke says:

      Personally I develop my own custom code for this ;) But if you aren’t a developer or can’t hire one you’ll need to look for a plugin that does this. I’m pretty sure that Gravity Forms can support editing custom user fields (but not 100% you’ll need to check).

      Admin
      1. Brandon Rhodes says:

        Gravity Forms *almost* does that. Almost. It’s beyond my kung fu level to hack something together, though. I *think* I figured out how to create what I was looking for, and it’s built in part off your code.

    2. Paul says:

      Looking to do the same as this. Brandon or AJ can you share any free or paid plugin that lets you do this or a tutorial that gives an idea on how it could be done? Thanks

      1. AJ Clarke says:

        Not sure what you mean Paul, this tutorial shows you how it’s done…

        Admin

Leave a Reply