How To Add A Custom Field To WordPress Registration

I just ran into this little dilemma while working on v3 of the plugin for the WLE sites. I needed to add a Country field to the registration process, as this is used to determine whether the new member joins WLE Pro or WLE World.

After much Google searching, I discovered two really annoying facts: (a) almost everyone who writes tutorials on this uses the existing ‘first name’ field, so it’s not a custom field and (b) those who do use a custom field write really weird code. So I figured it out myself.

I’m going to assume you know how to add a custom meta field to your user profile – if not, there are tons of good tutorials around. My custom field is called “user_country”.

I also have a function to build an array of available country names, so that I can just do a foreach{} to show them all in a <select> statement.

First, the hooks

You need three hooks to add a custom registration field, as follows:

add_action('user_register', 'register_country_field');

Next, the form

WordPress provides a standard registration form, so (much like when you create a custom user meta field), you just have to do the HTML that shows what you want. In my case, it’s a little more complex because I have a country list:

function wle_show_country_field() {
$user_country = ( isset( $_POST['user_country'] ) ) ? $_POST['user_country']: '';
$country_picker = wle_get_country_list();
<select name="user_country">
<option value=""></option>
<?php foreach ($country_picker as $country) {
if ($user_country == $country) {
$selected = 'selected'; }
else {
$selected = '';
echo '<option value="' . $country . '" ' . $selected . '>' . $country . '</option>';
} ?>

Apologies for the lack of indentation there – WordPress hates showing php tags. If you’re using a standard text field, you can replace the whole <select></select> part of that code with the normal <input></input> tags.

Check the input

Next, we need to make sure a country is selected. You’ll notice I added a blank at the top of the list so that it defaults to a blank entry. This bit’s really simple:

function wle_check_country_field($sanitized_user_login, $user_email, $errors) {
	if (empty($_POST['user_country'])) {
		$errors->add( 'user_country_error', __('ERROR: You must choose a country.','mydomain') );
	return $errors;

As an interesting side-note, the WP Codex shows the wrong parameter order in all the examples for this error code. You have to put $errors last, not first.

Store the data

And finally, we can store the selected value in the user’s meta:

function register_country_field($user_id) {
	if (isset($_POST['user_country'])) {
		update_user_meta($user_id, 'user_country', $_POST['user_country']);

I actually added another if statement into this function to determine which program the user is in by the country value selected.

Job done!

Bookmark the permalink.

Leave a Reply

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