How to add custom fields to the registration form in WordPress?

How to add custom fields to the registration form in WordPress?

  • 3
    Shares

 

If we want to learn more about subscribers of our website or if we need to have additional data for example: a marketing campaign, it may be useful to add a custom field or more fields to the WordPress registration form.

 

Such as?

In my case I added some essential data for my website in the registration form and are:  First Name, Last Name, Nickname and Consent to the Privacy Policy (Mandatory for all sites), obviously in your form you can insert many other mandatory fields according to the your needs but to make you the most understandable thing in this guide, I will focus only on the fields on the four fields that I added in my form. If you are involved in handling some code you can use or modify this code according to your needs, as I said before.

The code that you will find in this guide must be inserted in a file that you will call for ex. custom_form.php and the same file in a directory that you must create, is similar to that of the plugins in Wp-Content and that will be called mu-plugins (Must Use Plugins), soon there will be a guide on the mu -plugins.

 

1. How can I add a new item to the form?

 

We need to add a new element to the registration form as the very first thing to do and to get our result we need to use the register_form Hook, then we create new input fields for our additional data.

<?php add_action('register_form','myplugin_register_form');
 
    function myplugin_register_form (){
        $first_name = ( isset( $_POST['first_name'] ) ) ? $_POST['first_name']: ''; // Saving the First Name field
		$last_name = ( isset( $_POST['last_name'] ) ) ? $_POST['last_name']: ''; // Saving the Last Name field
		$nickname = ( isset( $_POST['nickname'] ) ) ? $_POST['nickname']: ''; // Saving the Nickname field
        $privacyPolicy = ( isset( $_POST['privacy_policy'] ) ) ? $_POST['privacy_policy']: '0'; // Saving the Privacy Policy field
        
		if (get_locale() == 'it_IT') {
        ?>
        <p>
            <label for="first_name"><?php _e('Nome','registrazione-utenti') ?><br />
                <input type="text" name="first_name" id="first_name" class="input" value="<?php echo esc_attr(stripslashes($first_name)); ?>" size="25" /></label>
        </p>
		<p>
            <label for="last_name"><?php _e('Cognome','registrazione-utenti') ?><br />
                <input type="text" name="last_name" id="last_name" class="input" value="<?php echo esc_attr(stripslashes($last_name)); ?>" size="25" /></label>
        </p>
		<p>
            <label for="nickname"><?php _e('Nickname','registrazione-utenti') ?><br />
                <input type="text" name="nickname" id="nickname" class="input" value="<?php echo esc_attr(stripslashes($nickname)); ?>" size="25" /></label>
        </p>
		<br>
		<p>
		<input type="checkbox" name="privacy_policy" value="1" aria-invalid="false" <?php if ($privacyPolicy == "1") { echo "checked"; } else { echo ""; } ?>></span></span></span> ACCETTO I <a href="https://www.sviluppomania.com/it/termsconditions/">TERMINI E CONDIZIONI D'USO</a> E L'<a href="https://www.sviluppomania.com/it/privacy/">INFORMATIVA SULLA PRIVACY</a>.</p>
		<br><br>
		</p>
		
		<?php } else { ?>
		
		<p>
            <label for="first_name"><?php _e('First Name','registrazione-utenti') ?><br />
                <input type="text" name="first_name" id="first_name" class="input" value="<?php echo esc_attr(stripslashes($first_name)); ?>" size="25" /></label>
        </p>
		<p>
            <label for="last_name"><?php _e('Last Name','registrazione-utenti') ?><br />
                <input type="text" name="surname" id="last_name" class="input" value="<?php echo esc_attr(stripslashes($last_name)); ?>" size="25" /></label>
        </p>
		<p>
            <label for="nickname"><?php _e('Nickname','registrazione-utenti') ?><br />
                <input type="text" name="nickname" id="nickname" class="input" value="<?php echo esc_attr(stripslashes($nickname)); ?>" size="25" /></label>
        </p>
		<br>
		<p>
		<input type="checkbox" name="privacy_policy" value="1" aria-invalid="false" <?php if ($privacyPolicy == "1") { echo "checked"; } else { echo ""; } ?>></span></span></span> I ACCEPT THE <a href="https://www.sviluppomania.com/en/termsconditions/">TERMS AND CONDITIONS OF USE</a> AND THE <a href="https://www.sviluppomania.com/en/privacy/">PRIVACY POLICY</a>.</p>
		<br><br>
		</p>
		
		<?php }
    }

 

All’interno del codice troverete anche una suddivisione per multilingua con il Plugin Qtranslate-X, il codice in questione è:

 

if (get_locale() == 'it_IT') {


<?php } else { ?>


<?php }

If you do not need this multi-language code for the aforementioned Plugin, just delete all the code that includes <? Php} else {?> Up to <? Php } and also delete if (get_locale () == 'it_IT') { so only the code for the Italian language will remain, you will find other pieces of code later on but if you follow our advice you will only have one in Italian.

 

 


2. How to validate the data entered?

It is not only necessary to enter data but also to check the validation (in our case First Name, Last Name, Nickname and PrivacyPolicy), we should use the Hook registration_errors, in this way control the field so that it is not empty as it must be mandatory. Depending on your needs, you can perform any checks on the data entered.

 

 

 

add_filter('registration_errors', 'myplugin_registration_errors', 10, 3);
    function myplugin_registration_errors ($errors, $sanitized_user_login, $user_email) {
 
        if ( empty( $_POST['first_name'] ) ) // The First Name field is mandatory and can not be empty
		{
			if (get_locale() == 'it_IT') {
				$errors->add( 'first_name_error', __('<strong>ERROR</strong>: Devi inserire il tuo Nome','registrazione-utenti') );
			} else {
				$errors->add( 'first_name_error', __('<strong>ERROR</strong>: Please, type your first name ','registrazione-utenti') );
			}
		}
			
		if ( empty( $_POST['last_name'] ) ) // The Last Name field is mandatory and can not be empty
		{
			if (get_locale() == 'it_IT') {
				$errors->add( 'last_name_error', __('<strong>ERROR</strong>: Devi inserire il tuo Cognome','registrazione-utenti') );	
			} else {
				$errors->add( 'last_name_error', __('<strong>ERROR</strong>: Please, type your last name','registrazione-utenti') );	
			}
		}
		
				if ( empty( $_POST['nickname'] ) ) // The Nickname field is mandatory and can not be empty
		{
			if (get_locale() == 'it_IT') {
				$errors->add( 'nickname_error', __('<strong>ERROR</strong>: Devi inserire il tuo Nickname','registrazione-utenti') );	
			} else {
				$errors->add( 'nickname_error', __('<strong>ERROR</strong>: Please, type your nickname','registrazione-utenti') );	
			}
		}

        if ( empty( $_POST['privacy_policy'] ) || $_POST['privacy_policy'] != "1") // Consent to the Privacy Policy is mandatory
		{
			if (get_locale() == 'it_IT') {
				$errors->add( 'privacy_policy_error', __('<strong>ERROR</strong>: Devi accettare l\'informativa sulla privacy','registrazione-utenti') );
			} else {
				$errors->add( 'privacy_policy_error', __('<strong>ERROR</strong>: Please, agree with the l\'Privacy Policy','registrazione-utenti') );
			}
		}
 
        return $errors;
    }

 


3. How to save the data of the user who has just registered?

 

New metadata for the new user must be saved, using the user_register Hook. The Hook allows us to access the information of the new user immediately after being added to the Database.

 

add_action('user_register', 'myplugin_user_register');
    function myplugin_user_register ($user_id) {
        if ( isset( $_POST['first_name'] ) )
            update_user_meta($user_id, 'first_name', $_POST['first_name']);
		if ( isset( $_POST['last_name'] ) )
            update_user_meta($user_id, 'last_name', $_POST['last_name']);
		if ( isset( $_POST['nickname'] ) )
            update_user_meta($user_id, 'nickname', $_POST['nickname']);
        if ( isset( $_POST['privacy_policy'] ) )
            update_user_meta($user_id, 'privacy_policy', $_POST['privacy_policy']);
    }

 

The user’s metadata is added by update_user_meta as soon as they are entered by passing its ID as parameters, the name of the meta value.

 


4. How to view data in the Back End?

Within the wp_usermeta table all data are saved, but they are not visible in the Back End, in our case you will not only see Privacy Policy, because the other changes use by default those of WordPress (eg $ first_name, $ last_name, etc ). To overcome this obstacle, we must create a special section for the Back End and be able to display additional information within the profile of each individual user. In the code below we make the data entered during the recording visible on the user profile page.

There are two different Hooks as you can see, because WordPress allows you to differentiate profile views depending on whether the site owner is viewing it, or another user. In our example we do not deal with this particular case study and the profile will simply appear with additional information.

 

 add_action('show_user_profile','show_the_new_meta_values'); // Hook used when a user is viewing their profile
 add_action('edit_user_profile','show_the_new_meta_values'); // Hook used when a user is viewing another user's profile
 
 function show_the_new_meta_values($user)
 {
 
    $privacyPolicy = get_user_meta($user->ID, 'privacy_policy', true);

    if (get_locale() == 'it_IT') { ?>
	<h3><?php _e('Informazioni aggiuntive','registrazione-utenti')?></h3>
		<table class="form-table">
            <tr>
				<th><label for="privacy_policy"><?php _e('Consenso informativa sulla Privacy Policy','registrazione-utenti') ?></label></th>
				<td><input type="checkbox" name="privacy_policy" value="1" aria-invalid="false" <?php if ($privacyPolicy == "1") { echo "checked"; } else { echo ""; } ?>><span> Consenso all'INFORMATIVA SULLA PRIVACY</span></td>
			</tr>
		</table>

	<?php } else { ?>
		
		<h3><?php _e('Additional information','registrazione-utenti')?></h3>
		<table class="form-table">
            <tr>
				<th><label for="privacy_policy"><?php _e('Consent information on the Privacy Policy','registrazione-utenti') ?></label></th>
				<td><input type="checkbox" name="privacy_policy" value="1" aria-invalid="false" <?php if ($privacyPolicy == "1") { echo "checked"; } else { echo ""; } ?>><span> Consent to the PRIVACY POLICY</span></td>
			</tr>
		</table>

	<?php }
 }

 

Our result will be this in the picture:

 

 


5. Our conclusions

 

Here is the complete code of our Guide:

 

<?php

/*
Plugin Name: WP Custom Register Form
Version: 1.0
Description: A simple plugin to customize the fields in the user registration of WordPress
Author: SviluppoMania.com
Author URI: http://www.sviluppomania.com
License: GPLv2 or later
License URI: http://www.gnu.org/licenses/gpl-2.0.html

==========================================

Licensing information

Copyright 2019 SviluppoMania (e-mail: [email protected])

This program is free software; you can redistribute it and / or modify
it under the terms of the GNU General Public License, version 2, as
published by the Free Software Foundation.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA

*/




/*
 * // Adding the new item to the registration form
 */
 
 
 // Adding the new item to the registration form
    add_action('register_form','myplugin_register_form');
 
    function myplugin_register_form (){
        $first_name = ( isset( $_POST['first_name'] ) ) ? $_POST['first_name']: ''; // Saving the First Name field
		$last_name = ( isset( $_POST['last_name'] ) ) ? $_POST['last_name']: ''; // Saving the Last Name field
		$nickname = ( isset( $_POST['nickname'] ) ) ? $_POST['nickname']: ''; // Saving the Nickname field
        $privacyPolicy = ( isset( $_POST['privacy_policy'] ) ) ? $_POST['privacy_policy']: '0'; // Saving the Privacy Policy field
        
		if (get_locale() == 'it_IT') {
        ?>
        <p>
            <label for="first_name"><?php _e('Nome','registrazione-utenti') ?><br />
                <input type="text" name="first_name" id="first_name" class="input" value="<?php echo esc_attr(stripslashes($first_name)); ?>" size="25" /></label>
        </p>
		<p>
            <label for="last_name"><?php _e('Cognome','registrazione-utenti') ?><br />
                <input type="text" name="last_name" id="last_name" class="input" value="<?php echo esc_attr(stripslashes($last_name)); ?>" size="25" /></label>
        </p>
		<p>
            <label for="nickname"><?php _e('Nickname','registrazione-utenti') ?><br />
                <input type="text" name="nickname" id="nickname" class="input" value="<?php echo esc_attr(stripslashes($nickname)); ?>" size="25" /></label>
        </p>
		<br>
		<p>
		<input type="checkbox" name="privacy_policy" value="1" aria-invalid="false" <?php if ($privacyPolicy == "1") { echo "checked"; } else { echo ""; } ?>></span></span></span> ACCETTO I <a href="https://www.sviluppomania.com/it/termsconditions/">TERMINI E CONDIZIONI D'USO</a> E L'<a href="https://www.sviluppomania.com/it/privacy/">INFORMATIVA SULLA PRIVACY</a>.</p>
		<br><br>
		</p>
		
		<?php } else { ?>
		
		<p>
            <label for="first_name"><?php _e('First Name','registrazione-utenti') ?><br />
                <input type="text" name="first_name" id="first_name" class="input" value="<?php echo esc_attr(stripslashes($first_name)); ?>" size="25" /></label>
        </p>
		<p>
            <label for="last_name"><?php _e('Last Name','registrazione-utenti') ?><br />
                <input type="text" name="surname" id="last_name" class="input" value="<?php echo esc_attr(stripslashes($last_name)); ?>" size="25" /></label>
        </p>
		<p>
            <label for="nickname"><?php _e('Nickname','registrazione-utenti') ?><br />
                <input type="text" name="nickname" id="nickname" class="input" value="<?php echo esc_attr(stripslashes($nickname)); ?>" size="25" /></label>
        </p>
		<br>
		<p>
		<input type="checkbox" name="privacy_policy" value="1" aria-invalid="false" <?php if ($privacyPolicy == "1") { echo "checked"; } else { echo ""; } ?>></span></span></span> I ACCEPT THE <a href="https://www.sviluppomania.com/en/termsconditions/">TERMS AND CONDITIONS OF USE</a> AND THE <a href="https://www.sviluppomania.com/en/privacy/">PRIVACY POLICY</a>.</p>
		<br><br>
		</p>
		
		<?php }
    }
 
    // Validation of the entered data
    add_filter('registration_errors', 'myplugin_registration_errors', 10, 3);
    function myplugin_registration_errors ($errors, $sanitized_user_login, $user_email) {
 
        if ( empty( $_POST['first_name'] ) ) // The First Name field is mandatory and can not be empty
		{
			if (get_locale() == 'it_IT') {
				$errors->add( 'first_name_error', __('<strong>ERROR</strong>: Devi inserire il tuo Nome','registrazione-utenti') );
			} else {
				$errors->add( 'first_name_error', __('<strong>ERROR</strong>: Please, type your first name ','registrazione-utenti') );
			}
		}
			
		if ( empty( $_POST['last_name'] ) ) // The Last Name field is mandatory and can not be empty
		{
			if (get_locale() == 'it_IT') {
				$errors->add( 'last_name_error', __('<strong>ERROR</strong>: Devi inserire il tuo Cognome','registrazione-utenti') );	
			} else {
				$errors->add( 'last_name_error', __('<strong>ERROR</strong>: Please, type your last name','registrazione-utenti') );	
			}
		}
		
				if ( empty( $_POST['nickname'] ) ) // The Nickname field is mandatory and can not be empty
		{
			if (get_locale() == 'it_IT') {
				$errors->add( 'nickname_error', __('<strong>ERROR</strong>: Devi inserire il tuo Nickname','registrazione-utenti') );	
			} else {
				$errors->add( 'nickname_error', __('<strong>ERROR</strong>: Please, type your nickname','registrazione-utenti') );	
			}
		}

        if ( empty( $_POST['privacy_policy'] ) || $_POST['privacy_policy'] != "1") // Consent to the Privacy Policy is mandatory
		{
			if (get_locale() == 'it_IT') {
				$errors->add( 'privacy_policy_error', __('<strong>ERROR</strong>: Devi accettare l\'informativa sulla privacy','registrazione-utenti') );
			} else {
				$errors->add( 'privacy_policy_error', __('<strong>ERROR</strong>: Please, agree with the l\'Privacy Policy','registrazione-utenti') );
			}
		}
 
        return $errors;
    }
	
 
    // Data saving
    add_action('user_register', 'myplugin_user_register');
    function myplugin_user_register ($user_id) {
        if ( isset( $_POST['first_name'] ) )
            update_user_meta($user_id, 'first_name', $_POST['first_name']);
		if ( isset( $_POST['last_name'] ) )
            update_user_meta($user_id, 'last_name', $_POST['last_name']);
		if ( isset( $_POST['nickname'] ) )
            update_user_meta($user_id, 'nickname', $_POST['nickname']);
        if ( isset( $_POST['privacy_policy'] ) )
            update_user_meta($user_id, 'privacy_policy', $_POST['privacy_policy']);
    }
 
 
 
 
/**************************************************
 *                                                *
 *   Display of additional data on the back end   *
 *                                                *
 *************************************************/
 
 
 add_action('show_user_profile','show_the_new_meta_values'); // Hook used when a user is viewing their profile
 add_action('edit_user_profile','show_the_new_meta_values'); // Hook used when a user is viewing another user's profile
 
 function show_the_new_meta_values($user)
 {
 
    $privacyPolicy = get_user_meta($user->ID, 'privacy_policy', true);

    if (get_locale() == 'it_IT') { ?>
	<h3><?php _e('Informazioni aggiuntive','registrazione-utenti')?></h3>
		<table class="form-table">
            <tr>
				<th><label for="privacy_policy"><?php _e('Consenso informativa sulla Privacy Policy','registrazione-utenti') ?></label></th>
				<td><input type="checkbox" name="privacy_policy" value="1" aria-invalid="false" <?php if ($privacyPolicy == "1") { echo "checked"; } else { echo ""; } ?>><span> Consenso all'INFORMATIVA SULLA PRIVACY</span></td>
			</tr>
		</table>

	<?php } else { ?>
		
		<h3><?php _e('Additional information','registrazione-utenti')?></h3>
		<table class="form-table">
            <tr>
				<th><label for="privacy_policy"><?php _e('Consent information on the Privacy Policy','registrazione-utenti') ?></label></th>
				<td><input type="checkbox" name="privacy_policy" value="1" aria-invalid="false" <?php if ($privacyPolicy == "1") { echo "checked"; } else { echo ""; } ?>><span> Consent to the PRIVACY POLICY</span></td>
			</tr>
		</table>

	<?php }
 }
 
 
 
 // Data update
add_action('personal_options_update', 'update_the_new_meta_values');
add_action('edit_user_profile_update', 'update_the_new_meta_values');
 
function update_the_new_meta_values($user_id)
{
    $new_value_first_name = $_POST['first_name'];
	$new_value_last_name = $_POST['last_name'];
	$new_value_nickname = $_POST['nickname'];
    $new_value_privacy_policy = $_POST['privacy_policy'];
 
 
    // Updated data
    update_user_meta($user_id,'first_name',$new_value_first_name);
	update_user_meta($user_id,'last_name',$new_value_last_name);
	update_user_meta($user_id,'nickname',$new_value_nickname);
    update_user_meta($user_id,'privacy_policy',$new_value_privacy_policy);
 
 
    // Check that the data has been saved in the Database
    if ( (get_user_meta($user_id, 'first_name', true ) != $new_value_first_name)
        || (get_user_meta($user_id, 'last_name', true ) != $new_value_last_name) || (get_user_meta($user_id, 'nickname', true ) != $new_value_nickname) || (get_user_meta($user_id, 'privacy_policy', true ) != $new_value_privacy_policy) ) {
        wp_die(__( 'Error while saving data on the Database','registrazione-utenti' ) );
    }
	
}

 

Every new user from now on who wishes to register on your site will have to insert some additional information, from the Back End you can easily check and / or modify the data entered for each user. I hope I have been clear, but if you have any doubts do not hesitate to contact us through our form contact us or comment on the article!

 

Stay Tuned!

 

 

 


  • 3
    Shares

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

Close Menu