I’m currently working on an application that requires users to register before logging into the site. The application is based on WordPress, but the registration process is using a custom template and requires some extra information.

As an example, I thought I’d share how I’m programmatically creating a user during the registration process, adding extra information to the user’s profile, and then displaying it in the user management dashboard.

Simplified Requirements

Add Custom User Meta During Registration

Examples like this have potential to be lengthy, so in order to keep in simple, let’s set the following requirements. I’m asking the user for:

  • First Name
  • Last Name
  • Email Address
  • Zip Code

WordPress natively supports fields for everything except a zip code so that’ll be the field that we use to add custom user meta.

Also note that there’s a lot of validation that occurs before successfully creating a user. You should always account for empty strings, well-formed email addresses, well-formed zip codes, and so on all of which are outside the scope of this particular post.

Secondly, this assumes that proper sanitization has been performed on each of the input fields. Nothing should ever be serialized to the database without being sanitized.

Add Custom User Meta During Registration

Assuming that all of the fields are valid (such as in the image above), you can begin programmatically creating the user.

Given that the input is stored in an array called $input, you can use the wp_insert_user function. Note that this function returns the ID of the user once it has been created:

$user_id = wp_insert_user(
	array(
		'user_login'	=>	$input['email_address'],
		'user_pass'	=>	wp_generate_password ( 12, false ),
		'first_name'	=>	$input['first_name'],
		'last_name'	=>	$input['last_name'],
		'user_email'	=>	$input['email_address'],
		'display_name'	=>	$input['first_name'] . ' ' . $input['last_name'],
		'nickname'	=>	$input['first_name'] . ' ' . $input['last_name'],
		'role'		=>	'None'
	)
);

Notice above that I’m also using wp_generate_password to automatically generate the user’s password.

Here’s the thing: Although I’m creating the user, I’ve yet to actually add the zip code to the user’s profile.

To do that, we can take advantage of update_user_meta. Since the wp_insert_user function returns the ID of the user that has just been created, we can easily associate a zip code with the user:

update_user_meta( $user_id, 'zip_code', $input['zip_code'] );

Easy enough, but what good is this if we aren’t able to see it in a dashboard?

Viewing The Custom User Meta

To view the custom user meta that was just added, we need to do two things:

  1. Add a new column to the users dashboard
  2. Render the zip code that’s associated with the current user

WordPress provides two hooks for doing just this: manage_users_columns and manage_users_custom_column.

First, we’ll add the new column to the user dashboard (note the function comments, too):

 /**
  * Adds a Zip Code column to the user display dashboard.
  *
  * @param	$columns	The array of columns that are displayed on the user dashboard
  * @return			The updated array of columns now including zip codes.
  */
 function theme_add_user_zip_code_column( $columns ) {

	 $columns['zip_code'] = __( 'Zip Code', 'theme' );
	 return $columns;

 } // end theme_add_user_zip_code_column
 add_filter( 'manage_users_columns', 'theme_add_user_zip_code_column' );

Next, we’ll return the zip code associated with the user that’s currently being passed into the manage_users_custom_column action. We’re assigning this function a priority of 10 and noting that it accepts three arguments all of which are documented in the comments:

 /**
  * Populates the Zip Code column with the specified user's zip code.
  *
  * @param	$value		An empty string
  * @param	$column_name	The name of the column to populate
  * @param	$user_id	The ID of the user for which we're working with
  * @return			The zip code associated with the user
  */
 function theme_show_user_zip_code_data( $value, $column_name, $user_id ) {

	 if( 'zip_code' == $column_name ) {
		 return get_user_meta( $user_id, 'zip_code', true );
	 } // end if

 } // end theme_show_user_zip_code_data
 add_action( 'manage_users_custom_column', 'theme_show_user_zip_code_data', 10, 3 );

Note that we’re only going to return a value if the column name that’s being passed as an argument equals that of the custom column created above.

Assuming you’ve done everything correctly, you should see the following dashboard:

Add Custom User Meta During Registration in WordPress

Notice that if the user doesn’t have a zip code, then nothing is returned and the dashboard doesn’t bomb out with any ugly notices. If, on the other hand, the user does have a zip code, it’ll write it out in the column we created.

Of course, this is a simple example of what can be done with user registration, custom user meta, and adding fields to the user dashboard.

Category:
Tips
Tags:

Join the conversation! 38 Comments

  1. Thanks a lot Tom.
    Was working like a charm.
    I then added some code to include my 2 MetaData in the default User Registration process and the loop is done.

    Chris

  2. Nice workaround ! I search a plugin, so i can the same, but easlier :)
    Have you an idea ?

  3. Hi,

    Do we need to change wp_user table structure? e.g If I want to add zipcode then do I need to add zipcode column in the wp_user table manually? I did the same thing you told above but I am not getting any data. Also as I checked the wp_user table it also not get altered with zipcode column.

  4. Let’s say that I want to create a page where one has access to profile as well as many other items. On top of the page I wish to have a sentence as “Hello “First Name”. Welcome to ….!

    From where do I pull out that First Name as variable? Thanks

  5. Thanks for the reply. I get it. I have the PHP code but my question is how to use it. Do I have to paste it on functions.php in child theme? and more important, how to make it work on a specific wordpress page?

  6. Hi Tom,
    Great article, and I used it to accordingly with WooCommerce.
    And the customer meta gets the right info.
    But how would I be able to use the additional fields in the customer-new-account.php email?
    Without altering the core files of WooCommerce?

    $new_customer_data = apply_filters( 'woocommerce_new_customer_data', array(
    'user_login' => $username,
    'user_pass' => $password,
    'user_email' => $email,
    'role' => 'customer'
    ) );
    $customer_id = wp_insert_user( $new_customer_data );
    if ( is_wp_error( $customer_id ) ) {
    return new WP_Error( 'registration-error', '<strong>' . __( 'ERROR', 'woocommerce' ) . '</strong>: ' . __( 'Couldn’t register you&hellip; please contact us if you continue to have problems.', 'woocommerce' ) );
    }
    do_action( 'woocommerce_created_customer', $customer_id, $new_customer_data, $password_generated );

  7. Hello Tom, thanks a lot for your great post!
    I would like to ask you information about sanization, because it always scares me.
    In my custom form registration, I don’t allow empty strings, I check forwell-formed email addresses and zip codes, but I still insert the information about user by my own, because of the danger of creatin big damage in database, if user inserts malware data. Do you have any advice about sanization regarding to user registration?
    THANKSSSSS!!! :)

  8. thanks a lot! I searched for this article whole day!

    thanks again and happy new year!

  9. one little question :-)

    i’ve added several columns using the first source code (copied 5 times and edited each variable)

    now, for the second source code it only shows the last copied column. How can I see all the content of the added columns?

    newbie question :-D

    thank you very much

    • Rather than copy and pasting the code five times, I would’ve recommended performing a loop that grabbed the proper ID (or whatever variable you were using) from a collection and then doing that.

      As far as seeing the content for the added columns, I’m a little confused by what you mean. Do you mean seeing the columns in the database or somewhere within WordPress?

  10. Hi Tom,

    How to integrate above code for frontend registration for the website.

    Thanks,

  11. Hi Tom,

    Great article..Thanks man!! Saved lots of time.

    I have one doubt – where do I have to code to show the user meta data in dashboard. You have given the code as how to show it but I’m quite new to wordpress, so I would appreciate if you can specify the file name.

  12. This is a half boiled solution (or half written). I use wp_insert_user() in my custom register form then put update_user_meta(), but no value stored. How can I get the proper $user_id for update_user_meta(), while zip code input field filled by the user during registration (along with username, password etc.)?

  13. I beg your attention on this stackexchange question:- http://wordpress.stackexchange.com/questions/92116/wp-update-user-doesnt-update-and-update-user-meta-does … what do you think? and with my problem as well?

  14. this code not work on my site……please reply me the files where should be code paste.

  15. Thanks lot Tom, You save my life. i have stuck on this task from last week and nothing can help me even famous tutorials are help less. But this method give me lot of knowledge and easy to understand now i am going to make registration with my other custom fields without any problem… once again thank you very much sir…stay blessed

  16. Nice post.

    a little question, how about i need more field. for example zip, genre and religion?

    i don’t think that will be like this :

    update_user_meta( $user_id, ‘zip_code’, $input[‘zip_code’] );

    update_user_meta( $user_id, ‘genre’, $input[‘genre’] );

    update_user_meta( $user_id, ‘religion’, $input[‘religion’] );

  17. I see this is a few years old but the tutorial seems to require the registration to be done by the administrator rather than the new user. Isn’t that so? I don’t see a front end form for the user to complete.

    • The tutorial is a few years old and I’d probably do a few things differently now, but the front-end form doesn’t exist on this post — it’s assumed it’s created and submitted, though. In terms of permissions, you can control that with a conditional using the current_user_can to check his/her capabilities.

  18. TOM Thank you very much. It helped in to my project and worked smooth.

  19. What file I can use for that code

    Thanks

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.