Use the coupon code WORDPRESS and save 30% OFF! Buy Now

How to add a custom user field in WordPress

Last Updated On
How to add a custom user field in WordPress WordPress template

WordPress stores user information out of the box, and it cares for the user’s name, email, and some more basic info, it leaves a lot to be desired. For example, social network links are pretty-much required these days, but since social networks come and go on a daily basis, WordPress itself can’t commit to supporting any single one as it may not exist tomorrow. A user’s date of birth is quite important for some websites as well (for example, with age-restricted content), however since a user’s date of birth may be considered confidential or identifying information, it may be illegal (or require special permits) in some countries. Again, WordPress won’t collect this information by itself in order to give us (its users) the freedom to use it no matter of our location. It therefore provides the means to build support for this extra information ourselves.

Building upon our previous tutorial, How to add custom fields to the WordPress registration form, were we collected the user’s year of birth upon registration and displayed it on the user’s profile page, we’ll now learn how to make this information editable so that the user itself (or an admin) can change it, because humans make mistakes all the time, even if it’s their own year of birth! Make sure you read the tutorial before reading this one, as we’ll be re-using and extending its code.

The code presented in this tutorial is also what’s needed for any custom user field that doesn’t need to be in the registration form. Just like the user’s name and surname!

Showing the user field

As mentioned in the registration form tutorial, actions ‘show_user_profile‘ and ‘edit_user_profile‘ are available for adding our own user fields. The former fires when users are seeing/editing their own profile information, while the latter fires when a user (such as an admin) sees/edits another user’s profile. Both actions pass a WP_User object as their sole parameter. Our previous code, which already uses those actions, was this:

add_action( 'show_user_profile', 'crf_show_extra_profile_fields' );
add_action( 'edit_user_profile', 'crf_show_extra_profile_fields' );

function crf_show_extra_profile_fields( $user ) {
?>
<h3><?php esc_html_e( 'Personal Information', 'crf' ); ?></h3>

<table class="form-table">
<tr>
<th><label for="year_of_birth"><?php esc_html_e( 'Year of birth', 'crf' ); ?></label></th>
<td><?php echo esc_html( get_the_author_meta( 'year_of_birth', $user->ID ) ); ?></td>
</tr>
</table>
<?php
}

Let’s go ahead and change the plain text year of birth, to an input element, so that it may accept user input.

add_action( 'show_user_profile', 'crf_show_extra_profile_fields' );
add_action( 'edit_user_profile', 'crf_show_extra_profile_fields' );

function crf_show_extra_profile_fields( $user ) {
$year = get_the_author_meta( 'year_of_birth', $user->ID );
?>
<h3><?php esc_html_e( 'Personal Information', 'crf' ); ?></h3>

<table class="form-table">
<tr>
<th><label for="year_of_birth"><?php esc_html_e( 'Year of birth', 'crf' ); ?></label></th>
<td>
<input type="number"
min="1900"
max="2017"
step="1"
id="year_of_birth"
name="year_of_birth"
value="<?php echo esc_attr( $year ); ?>"
class="regular-text"
/>
</td>
</tr>
</table>
<?php
}

Let’s check our profile page:

Note that I’m testing using a user which was registered in our previous tutorial, so the year of birth was provided during registration. If you’re trying it on a pre-existing user, the year of birth will be empty. It’s okay. Just fill it in and keep following the tutorial.

Validating the field

We can use the ‘user_profile_update_errors‘ action to validate and return errors to our form. It provides three parameters, $errors, $update and $user, that hold the errors, an update flag and a WP_User object respectively. Perhaps you remember that we’ve already used this action, in order to validate the admin-side user registration form (e.g. from an admin). The code we used in the tutorial was:

add_action( 'user_profile_update_errors', 'crf_user_profile_update_errors', 10, 3 );
function crf_user_profile_update_errors( $errors, $update, $user ) {
if ( $update ) {
return;
}

if ( empty( $_POST['year_of_birth'] ) ) {
$errors->add( 'year_of_birth_error', __( '<strong>ERROR</strong>: Please enter your year of birth.', 'crf' ) );
}

if ( ! empty( $_POST['year_of_birth'] ) && intval( $_POST['year_of_birth'] ) < 1900 ) {
$errors->add( 'year_of_birth_error', __( '<strong>ERROR</strong>: You must be born after 1900.', 'crf' ) );
}
}

Lines 3-5 checked that if the request was for updating a user (not applicable at that tutorial, since it was about the registration form), and if it was, it just bailed. Well, in this tutorial we want it to apply both on the registration and when updating user fields so we can just remove those lines altogether.

add_action( 'user_profile_update_errors', 'crf_user_profile_update_errors', 10, 3 );
function crf_user_profile_update_errors( $errors, $update, $user ) {
if ( empty( $_POST['year_of_birth'] ) ) {
$errors->add( 'year_of_birth_error', __( '<strong>ERROR</strong>: Please enter your year of birth.', 'crf' ) );
}

if ( ! empty( $_POST['year_of_birth'] ) && intval( $_POST['year_of_birth'] ) < 1900 ) {
$errors->add( 'year_of_birth_error', __( '<strong>ERROR</strong>: You must be born after 1900.', 'crf' ) );
}
}

If we wanted to only validate when updating, because for example the field wasn’t present in the registration form, the we would have negate the if() statement instead.

Now, if we try and enter an invalid value, e.g. 1800:

Saving the field

Just like the ‘show_user_profile‘ and ‘edit_user_profile‘ actions mentioned earlier, actions ‘personal_options_update‘ and ‘edit_user_profile_update‘ fire when the “Update profile” button is pressed, when updating your own or another user’s respectively. Both actions pass the modified user’s ID, so we can handle both cases with just one function:

add_action( 'personal_options_update', 'crf_update_profile_fields' );
add_action( 'edit_user_profile_update', 'crf_update_profile_fields' );

function crf_update_profile_fields( $user_id ) {
if ( ! current_user_can( 'edit_user', $user_id ) ) {
return false;
}

if ( ! empty( $_POST['year_of_birth'] ) && intval( $_POST['year_of_birth'] ) >= 1900 ) {
update_user_meta( $user_id, 'year_of_birth', intval( $_POST['year_of_birth'] ) );
}
}

We just need to make sure thing of two things:

  1. The current user has the right to modify the user in question (line 5), and
  2. The field has a valid value. The related code inside the crf_user_profile_update_errors() function, merely appends the error notifications on screen. Execution continues normally though, and if we don’t make sure the value is valid before saving it (line 9), we’re going to end up with bad values, sooner than later.

You can now test that any changes you make to the year of birth field are persisting properly!

Wrapping it up

Due to referring back to the plugin built in the previous tutorial, it may not be clear how you’d go about adding the year of birth just as a user profile field, ignoring any previous code, tutorials, etc. This is how you’d add the field:

<?php
/*
Plugin Name: Custom Profile Fields
Plugin URI:
Description:
Version: 0.1
Author: CSSIgniter
Author URI:
License: GPLv2 or later
License URI: http://www.gnu.org/licenses/gpl-2.0.html
*/

add_action( 'show_user_profile', 'crf_show_extra_profile_fields' );
add_action( 'edit_user_profile', 'crf_show_extra_profile_fields' );

function crf_show_extra_profile_fields( $user ) {
$year = get_the_author_meta( 'year_of_birth', $user->ID );
?>
<h3><?php esc_html_e( 'Personal Information', 'crf' ); ?></h3>

<table class="form-table">
<tr>
<th><label for="year_of_birth"><?php esc_html_e( 'Year of birth', 'crf' ); ?></label></th>
<td>
<input type="number"
min="1900"
max="2017"
step="1"
id="year_of_birth"
name="year_of_birth"
value="<?php echo esc_attr( $year ); ?>"
class="regular-text"
/>
</td>
</tr>
</table>
<?php
}

add_action( 'user_profile_update_errors', 'crf_user_profile_update_errors', 10, 3 );
function crf_user_profile_update_errors( $errors, $update, $user ) {
if ( ! $update ) {
return;
}

if ( empty( $_POST['year_of_birth'] ) ) {
$errors->add( 'year_of_birth_error', __( '<strong>ERROR</strong>: Please enter your year of birth.', 'crf' ) );
}

if ( ! empty( $_POST['year_of_birth'] ) && intval( $_POST['year_of_birth'] ) < 1900 ) {
$errors->add( 'year_of_birth_error', __( '<strong>ERROR</strong>: You must be born after 1900.', 'crf' ) );
}
}


add_action( 'personal_options_update', 'crf_update_profile_fields' );
add_action( 'edit_user_profile_update', 'crf_update_profile_fields' );

function crf_update_profile_fields( $user_id ) {
if ( ! current_user_can( 'edit_user', $user_id ) ) {
return false;
}

if ( ! empty( $_POST['year_of_birth'] ) && intval( $_POST['year_of_birth'] ) >= 1900 ) {
update_user_meta( $user_id, 'year_of_birth', intval( $_POST['year_of_birth'] ) );
}
}

And this is what it looks like if it’s included in the plugin that we previously developed on the registration form tutorial:

<?php
/*
Plugin Name: Custom Registration Fields
Plugin URI:
Description:
Version: 0.1
Author: CSSIgniter
Author URI:
License: GPLv2 or later
License URI: http://www.gnu.org/licenses/gpl-2.0.html
*/

/**
* Front end registration
*/

add_action( 'register_form', 'crf_registration_form' );
function crf_registration_form() {

$year = ! empty( $_POST['year_of_birth'] ) ? intval( $_POST['year_of_birth'] ) : '';

?>
<p>
<label for="year_of_birth"><?php esc_html_e( 'Year of birth', 'crf' ) ?><br/>
<input type="number"
min="1900"
max="2017"
step="1"
id="year_of_birth"
name="year_of_birth"
value="<?php echo esc_attr( $year ); ?>"
class="input"
/>
</label>
</p>
<?php
}

add_filter( 'registration_errors', 'crf_registration_errors', 10, 3 );
function crf_registration_errors( $errors, $sanitized_user_login, $user_email ) {

if ( empty( $_POST['year_of_birth'] ) ) {
$errors->add( 'year_of_birth_error', __( '<strong>ERROR</strong>: Please enter your year of birth.', 'crf' ) );
}

if ( ! empty( $_POST['year_of_birth'] ) && intval( $_POST['year_of_birth'] ) < 1900 ) {
$errors->add( 'year_of_birth_error', __( '<strong>ERROR</strong>: You must be born after 1900.', 'crf' ) );
}

return $errors;
}

add_action( 'user_register', 'crf_user_register' );
function crf_user_register( $user_id ) {
if ( ! empty( $_POST['year_of_birth'] ) ) {
update_user_meta( $user_id, 'year_of_birth', intval( $_POST['year_of_birth'] ) );
}
}

/**
* Back end registration
*/

add_action( 'user_new_form', 'crf_admin_registration_form' );
function crf_admin_registration_form( $operation ) {
if ( 'add-new-user' !== $operation ) {
// $operation may also be 'add-existing-user'
return;
}

$year = ! empty( $_POST['year_of_birth'] ) ? intval( $_POST['year_of_birth'] ) : '';

?>
<h3><?php esc_html_e( 'Personal Information', 'crf' ); ?></h3>

<table class="form-table">
<tr>
<th><label for="year_of_birth"><?php esc_html_e( 'Year of birth', 'crf' ); ?></label> <span class="description"><?php esc_html_e( '(required)', 'crf' ); ?></span></th>
<td>
<input type="number"
min="1900"
max="2017"
step="1"
id="year_of_birth"
name="year_of_birth"
value="<?php echo esc_attr( $year ); ?>"
class="regular-text"
/>
</td>
</tr>
</table>
<?php
}

add_action( 'user_profile_update_errors', 'crf_user_profile_update_errors', 10, 3 );
function crf_user_profile_update_errors( $errors, $update, $user ) {
if ( empty( $_POST['year_of_birth'] ) ) {
$errors->add( 'year_of_birth_error', __( '<strong>ERROR</strong>: Please enter your year of birth.', 'crf' ) );
}

if ( ! empty( $_POST['year_of_birth'] ) && intval( $_POST['year_of_birth'] ) < 1900 ) {
$errors->add( 'year_of_birth_error', __( '<strong>ERROR</strong>: You must be born after 1900.', 'crf' ) );
}
}

add_action( 'edit_user_created_user', 'crf_user_register' );


/**
* Back end display
*/

add_action( 'show_user_profile', 'crf_show_extra_profile_fields' );
add_action( 'edit_user_profile', 'crf_show_extra_profile_fields' );

function crf_show_extra_profile_fields( $user ) {
$year = get_the_author_meta( 'year_of_birth', $user->ID );
?>
<h3><?php esc_html_e( 'Personal Information', 'crf' ); ?></h3>

<table class="form-table">
<tr>
<th><label for="year_of_birth"><?php esc_html_e( 'Year of birth', 'crf' ); ?></label></th>
<td>
<input type="number"
min="1900"
max="2017"
step="1"
id="year_of_birth"
name="year_of_birth"
value="<?php echo esc_attr( $year ); ?>"
class="regular-text"
/>
</td>
</tr>
</table>
<?php
}

add_action( 'personal_options_update', 'crf_update_profile_fields' );
add_action( 'edit_user_profile_update', 'crf_update_profile_fields' );

function crf_update_profile_fields( $user_id ) {
if ( ! current_user_can( 'edit_user', $user_id ) ) {
return false;
}

if ( ! empty( $_POST['year_of_birth'] ) && intval( $_POST['year_of_birth'] ) >= 1900 ) {
update_user_meta( $user_id, 'year_of_birth', intval( $_POST['year_of_birth'] ) );
}
}

44 responses to “How to add a custom user field in WordPress”

  1. Hi,

    Im just trying to figure out how to change this from a number field to just a plain text one. I’ve tried and it works on the registration page but in the admin I’m just seeing the result 0.

    Any idea how to acheive this?

    • Anastis Sourgoutsidis says:

      You’ll need to change the validation and sanitization code accordingly.
      For example, you don’t want to sanitize with intval() any more, as it forces the value to become a number (that’s why you get a 0). Try using sanitize_text_field() instead.

  2. Sophie says:

    Hi,

    Thank you for the tutorial, I’ve just managed to put there a text input instead of the numeric one. But can I add there more fields without cutting the loop? How to do it?

  3. jose ramirez says:

    Hi, I’m learning about the hooks, this article was a little more difficult to grasp than the previous because the access for the edit user page and edit admin page, but other than that it’s an amazing tutorial, I like to change the variable, functions and values when I’m learning something new, just to make sure that I fully understand the concepts, I found that this line of code is not necessary(at least the plugin works as suppose to):

    add_action( ‘edit_user_created_user’, ‘crf_user_register’ );

    I tested as user and as admin, changing the year number, also tested creating new users, and the hook makes no difference(same with the previous tutorial), could explain why allows to save and if its not necessary what other hook is doing the update of info?

    Thank you.

  4. jose ramirez says:

    Disregard my last message, from line 95 to 104 does the validation.

    I’m starting to like a lot this WP functions:

    user_profile_update_errors
    registration_errors
    update_user_meta
    get_the_author_meta

    so easy to do validations and to update and get data, its amazing.

  5. Kazeem says:

    Great article.
    I am using the code above(edited) but with drop down options. the selected options from the drop down is being saved in the database, but when editing, the display defaults to the first option value, not the selected one.
    Do you mind giving a sample code of how to go about displaying the saved value when the user edits his profile.
    Thanks.

    • Anastis Sourgoutsidis says:

      Each option needs a call to selected(). The related codex page includes an example on how you’d go about it.
      Hope this helps.

      • Marko says:

        I know this is an old post but can anyone give me bit more guidance on this.

        I have this code this piece of code:
        http://prntscr.com/rlofjp

        What ever field I choose and save it reverts to the first value “Sarajevski”.
        Can anyone help?

        Thanks in advance

        • Anastis Sourgoutsidis says:

          The values that your options have ( value=”Sarajevski” ) are different than the values you are comparing with ( selected( $regija, ‘sarajevski’ ) ).

          Once you change all value=”” attributes to match the correct string, it should work.

        • Mehmet says:

          Hello, how can I make the front end profile editing page with these codes?

          • Anastis Sourgoutsidis says:

            You can’t.
            This code uses the forms and actions that WordPress provides on the back-end, and depend on them.

            For the front-end, you need to implement your own forms.

  6. suresh kumar says:

    I am working on a medical reporting site in wordpress, where the requirement is that admin
    can upload a seperate .pdf file to different users’ profile & only the profile owner can download it

    • Anastis Sourgoutsidis says:

      In this case, a user field is only appropriate for storing the path to the file or other related metadata. File security is not something WordPress does by default (all files in wp-content/uploads/ are downloadable by default), so you’ll need to look into a specialized plugin, or implement a whole bunch of security measures, including proper web server configuration. This StackExchange thread should point you to the right direction.

  7. Ana says:

    Hi there. Thanks for the excellent tutorial. It works perfectly.
    Sorry for the noob question, that’s my first time coding. Is that possible to show this field in user profile? If yes, how should I call it? What If I want a variable to recieve the value so I can use in another page in the wordpress? Thanks!

    • Anastis Sourgoutsidis says:

      You can use get_user_meta() to grab the value whenever you need it.
      E.g.:

      $year = get_user_meta( $user_id, 'year_of_birth', true );
      • Ana says:

        Thanks again for your kindly support. Everything works just fine.
        I’m back just to say that you wrote right the function first but you misstyped the code latter.

        You typed: $year = geR_user_meta….
        Instead of: $year = geT_user_meta…..

        It took me a while to realize, so I’m here saying it just to help anyone who is so distracted as I am.

        Thanks again, you saved me! <3

  8. Purushothaman J says:

    Hi, the tutorial was great. it helped me an clear understanding on how the additional fields addition works. and also retrieves the data.

    i need another help.

    i want to show billing fields and other fields like mobile number, address line1 , address line 2, city, postcode, state, country…

    these fields are which are pulled into the billing address if an new order is created in backend by admin..

    I explained in this screenshot here..: https://prnt.sc/kwt93k

    Actually now the Shop Role does steps like -> add user -> save -> add new order -> type three letters -> selects customer name from dropdown -> then fill billing details and other details mentioned above.. -> only email and name is fetched as we entered while creating the user.

    I want to change like this -> add user -> enter all required details for billing ( fields in screenshot ) -> save -> add new order -> type three letters -> selects customer name from dropdown -> then all details are auto fetched as we entered while creating the user.

    this is want i want to achieve.. so how to add code so that i shows billing & other fields which are already there in wordpress.

    kindly help me.

    Thank you.

    • Anastis Sourgoutsidis says:

      I don’t know how you implemented your system, but I guess you have some kind of AJAX action that returns the user’s email and name. When that information is fetched, you probably can also get the user’s ID, which you can use to fetch any other user information you need by using either the get_the_author_meta() or the get_user_meta() function.
      Just make sure you pass the correct user ID (the one you just fetched), otherwise you might end up with the information of the user that is currently logged in and doing the data entry.

  9. Hi Anastis,

    Thanks for the tutorial. Works like a charm. It is easy, especially since I use Code Snippets.

    I understand from the first comment in this thread that I can add as many fields that I want.

    But I just don’t know how.

    Say, I want to keep the birthday field (from your code) and now I want to add, say, a gender field.

    How can I integrate both fields in the same code?

    I specify that I only use the part of the code for the backend registration. I am not interested at the moment by the frontend registration. So, I’m using only the “backend registration” and “backend display” parts from your code.

    So, do I had to start a new code section at the end of the “birthday code section” or do I have to intermix “birthday field code” and “gender field code”?

    Thanks a lot,

    François Maurice

    • Anastis Sourgoutsidis says:

      Hi François,
      you don’t need to add any other functions or hooks. Just use the ones you already have.
      For example, in the “Showing the user field” section, the gender field will be a new <tr> entry in the existing table. Similarly, in the “Validating the field” and “Saving the field” sections, you’ll just add some new if() statements inside the existing functions, following the pattern of the example.
      Hope this helps.

      • Hi Anastis,

        Works nicely !! Thanks a lot. I can now add as many fields as I want to the backend users profile.

        I’m not sure if you permit this, but here’s the code as an example for those interested to add more than one field in one shot. I added a gender field with input type “radio button”:

        <input type="number"
        min="1900"
        max="2017"
        step="1"
        id="year_of_birth"
        name="year_of_birth"
        value="”
        class=”regular-text”
        />

        <input type="radio" name="genres"

        value=”Femme”>Femme
        <input type="radio" name="genres"

        value=”Homme”>Homme

        add( ‘year_of_birth_error’, __( ‘ERROR: Please enter your year of birth.’, ‘crf’ ) );
        }

        if ( ! empty( $_POST[‘year_of_birth’] ) && intval( $_POST[‘year_of_birth’] ) add( ‘year_of_birth_error’, __( ‘ERROR: You must be born after 1900.’, ‘crf’ ) );
        }

        if ( empty( $_POST[‘genres’] ) ) {
        $errors->add( ‘genres_error’, __( ‘ERROR: Please enter your gender.’, ‘crf’ ) );
        }

        }

        add_action( ‘edit_user_created_user’, ‘crf_user_register’ );

        /* BACKEND DISPLAY */

        add_action( ‘show_user_profile’, ‘crf_show_extra_profile_fields’ );
        add_action( ‘edit_user_profile’, ‘crf_show_extra_profile_fields’ );

        function crf_show_extra_profile_fields( $user ) {
        $year = get_the_author_meta( ‘year_of_birth’, $user->ID );
        $genre = get_the_author_meta( ‘genres’, $user->ID );
        ?>

        <input type="number"
        min="1900"
        max="2017"
        step="1"
        id="year_of_birth"
        name="year_of_birth"
        value="”
        class=”regular-text”
        />

        <input type="radio" name="genres"

        value=”Femme”>Femme
        <input type="radio" name="genres"

        value=”Homme”>Homme

        = 1900 ) {
        update_user_meta( $user_id, ‘year_of_birth’, intval( $_POST[‘year_of_birth’] ) );
        }
        if ( ! empty( $_POST[‘genres’] )) {
        update_user_meta( $user_id, ‘genres’, sanitize_text_field( $_POST[‘genres’] ) );
        }
        }

        • Oops. Sorry, a small bug in the code above. Here’s the corrected code:

          <input type="number"
          min="1900"
          max="2017"
          step="1"
          id="year_of_birth"
          name="year_of_birth"
          value="”
          class=”regular-text”
          />

          <input type="radio"
          id="genres"
          name="genres"
          class="regular-text"

          value=”Femme”>Femme
          <input type="radio"
          id="genres"
          name="genres"
          class="regular-text"

          value=”Homme”>Homme

          add( ‘year_of_birth_error’, __( ‘ERROR: Please enter your year of birth.’, ‘crf’ ) );
          }

          if ( ! empty( $_POST[‘year_of_birth’] ) && intval( $_POST[‘year_of_birth’] ) add( ‘year_of_birth_error’, __( ‘ERROR: You must be born after 1900.’, ‘crf’ ) );
          }

          if ( empty( $_POST[‘genres’] ) ) {
          $errors->add( ‘genres_error’, __( ‘ERROR: Please enter your gender.’, ‘crf’ ) );
          }

          }

          add_action( ‘edit_user_created_user’, ‘crf_user_register’ );

          /* BACKEND DISPLAY */

          add_action( ‘show_user_profile’, ‘crf_show_extra_profile_fields’ );
          add_action( ‘edit_user_profile’, ‘crf_show_extra_profile_fields’ );

          function crf_show_extra_profile_fields( $user ) {
          $year = get_the_author_meta( ‘year_of_birth’, $user->ID );
          $genre = get_the_author_meta( ‘genres’, $user->ID );
          ?>

          <input type="number"
          min="1900"
          max="2017"
          step="1"
          id="year_of_birth"
          name="year_of_birth"
          value="”
          class=”regular-text”
          />

          <input type="radio"
          id="genres"
          name="genres"
          class="regular-text"

          value=”Femme”>Femme
          <input type="radio"
          id="genres"
          name="genres"
          class="regular-text"

          value=”Homme”>Homme

          = 1900 ) {
          update_user_meta( $user_id, ‘year_of_birth’, intval( $_POST[‘year_of_birth’] ) );
          }
          if ( ! empty( $_POST[‘genres’] )) {
          update_user_meta( $user_id, ‘genres’, sanitize_text_field( $_POST[‘genres’] ) );
          }
          }

          • Olivier says:

            Hi!

            Very useful!

            How do I get a radio button value to show in the profile?

            I have:

            <input type="radio"
            id="asunnon_rappu"
            name="asunnon_rappu"
            value="”
            class=”regular-text”
            />A
            <input type="radio"
            id="asunnon_rappu"
            name="asunnon_rappu"
            value="”
            class=”regular-text”
            />B
            <input type="radio"
            id="asunnon_rappu"
            name="asunnon_rappu"
            value="”
            class=”regular-text”
            />C

            Although the value is saved correctly, I’m not able to get the right radio button to turn on :-)

          • Anastis Sourgoutsidis says:

            Hi Olivier,
            In order to have a checkbox be preselected, you need to set the checked boolean attribute on the input that you want to be preselected.
            You do that with the checked() function in WordPress. You pass two parameters. One is the variable that holds the value of the selected checkbox, and the other is the value of the specific checkbox.
            Therefore, in your example, you would need to replace the first input’s value=”” attribute with something like value=”a”

  10. Denis says:

    Hi guys, I have a little problem with wordpress.

    i’ve managed to add new fields in the user menu, create the new fields.
    in the section Manage users i also created the fields so that they are displayed from the section Add new, but they are not automatically touched like first name and last name.

    what can i do ? the areas i changed are marked with #.

    greetings Denis

    user-new.php

    <input name="user_login" type="text" id="user_login" value="” aria-required=”true” autocapitalize=”none” autocorrect=”off” maxlength=”60″ />

    <input name="email" type="email" id="email" value="” />

    ############################################################################################################################################################

    <input name="firma" type="text" id="firma" value="” />

    <input name="adresszeile_1" type="text" id="adresszeile_1" value="” />

    <input name="adresszeile_2" type="text" id="adresszeile_2" value="” />

    <input name="stadt" type="text" id="stadt" value="” />

    <input name="postleitzahl" type="text" id="postleitzahl" value="” />

    ############################################################################################################################################################

    user-edit.php

    ############################################################################################################################################################

    <input type="text" name="firma" id="firma" value="firma) ?>” class=”regular-text” />

    <input type="text" name="adresszeile_1" id="adresszeile_1" value="adresszeile_1) ?>” class=”regular-text” />

    <input type="text" name="adresszeile_2" id="adresszeile_2" value="adresszeile_2) ?>” class=”regular-text” />

    <input type="text" name="stadt" id="stadt" value="stadt) ?>” class=”regular-text” />

    <input type="text" name="postleitzahl" id="postleitzahl" value="postleitzahl) ?>” class=”regular-text” />

    ############################################################################################################################################################

    <input type="text" name="first_name" id="first_name" value="first_name) ?>” class=”regular-text” />

    <input type="text" name="last_name" id="last_name" value="last_name) ?>” class=”regular-text” />

    <input type="text" name="nickname" id="nickname" value="nickname) ?>” class=”regular-text” />

    user_firma;
    $public_display[‘display_adresszeile_1’] = $profileuser->user_adresszeile_1;
    $public_display[‘display_adresszeile_2’] = $profileuser->user_adresszeile_2;
    $public_display[‘display_stadt’] = $profileuser->user_stadt;
    $public_display[‘display_postleitzahl’] = $profileuser->user_postleitzahl;

    ############################################################################################################################################################

    $public_display[‘display_nickname’] = $profileuser->nickname;
    $public_display[‘display_username’] = $profileuser->user_login;

    if ( !empty($profileuser->first_name) )
    $public_display[‘display_firstname’] = $profileuser->first_name;

    ############################################################################################################################################################

    if ( !empty($profileuser->firma) )
    $public_display[‘display_firma’] = $profileuser->firma;

    if ( !empty($profileuser->adresszeile_1) )
    $public_display[‘display_adresszeile_1’] = $profileuser->adresszeile_1;

    if ( !empty($profileuser->adresszeile_2) )
    $public_display[‘display_adresszeile_2’] = $profileuser->adresszeile_2;

    if ( !empty($profileuser->stadt) )
    $public_display[‘display_stadt’] = $profileuser->stadt;

    if ( !empty($profileuser->postleitzahl) )
    $public_display[‘display_postleitzahl’] = $profileuser->postleitzahl;

    ############################################################################################################################################################

    if ( !empty($profileuser->last_name) )
    $public_display[‘display_lastname’] = $profileuser->last_name;

    if ( !empty($profileuser->first_name) && !empty($profileuser->last_name) ) {
    $public_display[‘display_firstlast’] = $profileuser->first_name . ‘ ‘ . $profileuser->last_name;
    $public_display[‘display_lastfirst’] = $profileuser->last_name . ‘ ‘ . $profileuser->first_name;
    }

    if ( !in_array( $profileuser->display_name, $public_display ) ) // Only add this if it isn’t duplicated elsewhere
    $public_display = array( ‘display_displayname’ => $profileuser->display_name ) + $public_display;

  11. Kermit Richardson says:

    I think in this area it should be “edit_users” not “edit_user”

    This worked for me, mine is a secure admin only set field

    if ( ! current_user_can( ‘edit_users’, $user_id ) ) {
    return false;
    }

    • Anastis Sourgoutsidis says:

      Well, it depends.
      The ‘edit_user’ capability is true when a user can edit his/her own profile, and ‘edit_users’ when a user can edit other users’ profile as well (i.e. an admin).
      Depending on the use-case, one might be more appropriate than the other.

  12. Alexei says:

    I decided to try using type = “date” but as a result I get dd.mm.yyyy without a specified date when registering a user. How can this be fixed?

    • Nik Vourvachis says:

      Hello. Provided that you have set up the input correctly you will then need to save the value properly. Line 65 in the original Custom Profile Fields file, should change to something like this update_user_meta( $user_id, 'year_of_birth', date( 'Y-m-d', strtotime( $_POST['year_of_birth'] ) ) ); this will save the value. Then you will need to handle errors for improper date submissions according to your needs.

  13. Nicolas says:

    Hey,

    Thanks for the tuto It helped me a lot !

    I tried use this in a different way to select region.
    I have the choice between many regions but what ever the region I save it’s always the same that showed up.

    <option value="”>Franche-Comté
    <option value="”>Rhones-Alpes

    function crf_update_profile_fields( $user_id ) {
    if ( ! current_user_can( ‘edit_user’, $user_id ) ) {
    return false;
    }

    if ( ! empty( $_POST[‘region’] ) ) {
    update_user_meta( $user_id, ‘region’, sanitize_text_field( $_POST[‘region’] ) );
    }
    }

    Thanks for the help

    • Anastis Sourgoutsidis says:

      You need to add code that pre-selects the appropriate value.
      For example:

      <?php $region = get_user_meta( $user_id, 'region', true ); ?>
      <option value="franche-compte" <?php selected( 'franche-compte', $region ); ?>>Franche-Comté</option>
      <option value="rhones-alpes"  <?php selected( 'rhones-alpes', $region ); ?>>Rhones-Alpes</option>
      
      
  14. bastien Migette says:

    Thanks, it was exactly what I was looking for !!

  15. henrique says:

    Hi mate. I read both tutorials and im still having an issue.
    I was trying to change year of birth for whatsapp and I though I changed something wrongly. Then I ust copied and pasted the whole code you provided with year or birth actually and everythin works fine except wordpress is not saving any value to the field.

    I use one plugin that twiks a bit the login screen. Could that be the problem? Cheers

    • Anastis Sourgoutsidis says:

      It could be, but it’s impossible for me to tell.

      You could try hardcoding a value with update_user_meta() inside crf_user_register(), outside of any if statements.
      If the value gets saved into the DB, then the problem must be something earlier in the process that makes $_POST[‘year_of_birth’] reach the function without a value.

  16. Patricio Cifuentes says:

    Great code, thanx for sharing, i have a question; is possible to add a number field with unique data, example, when a register a user i have to fill the field Social Security number, if it already exist shows an error.

    • Anastis Sourgoutsidis says:

      Testing for uniqueness is just another validation step, therefore you should add it as another check inside the crf_registration_errors() function.
      You will need to make a new WP_User_Query() using its ‘meta_key’ and ‘meta_value’ arguments to see if a user with this particular SSN exists, and add an $errors->add() call if it does.

  17. mohsen35 says:

    I love you man. you are the only one who showed how to do this by not using a plugin.

  18. Kelvin says:

    Im trying to put only a simple number field, since I want to give to my users a code to register, but cant make it work the registration goes through without validating the field

  19. Kelvin says:

    I have this code in order to add a registration code but it doesnt work.

    <input type="number"
    step="1"
    id="year_of_birth"
    name="year_of_birth"
    value="”
    class=”input”
    />

    add( ‘registration_code’, __( ‘ERROR: Please enter the registration code’, ‘crf’ ) );
    }

    // if ( ! empty( $_POST[‘registration_code’] ) && intval( $_POST[‘registration_code’] ) add( ‘year_of_birth_error’, __( ‘ERROR: You must be born after 1900.’, ‘crf’ ) );
    // }

    return $errors;
    }

    // Sanitizing and saving the field

    add_action( ‘user_register’, ‘crf_user_register’ );
    function crf_user_register( $user_id ) {
    if ( ! empty( $_POST[‘registration_code’] ) ) {
    update_user_meta( $user_id, ‘registration_code’, intval( $_POST[‘registration_code’] ) );
    }
    }

    /**
    * Back end registration
    */

    add_action( ‘user_new_form’, ‘crf_admin_registration_form’ );
    function crf_admin_registration_form( $operation ) {
    if ( ‘add-new-user’ !== $operation ) {
    // $operation may also be ‘add-existing-user’
    return;
    }

    $r_code = ! empty( $_POST[‘registration_code’] ) ? intval( $_POST[‘registration_code’] ) : ”;

    ?>

    <input type="number"
    step="1"
    id="year_of_birth"
    name="year_of_birth"
    value="”
    class=”input”
    />

    add( ‘registration_code’, __( ‘ERROR: Please enter the registration code.’, ‘crf’ ) );
    }

    // if ( ! empty( $_POST[‘year_of_birth’] ) && intval( $_POST[‘year_of_birth’] ) add( ‘year_of_birth_error’, __( ‘ERROR: You must be born after 1900.’, ‘crf’ ) );
    // }
    }

    add_action( ‘edit_user_created_user’, ‘crf_user_register’ );

    add_action( ‘show_user_profile’, ‘crf_show_extra_profile_fields’ );
    add_action( ‘edit_user_profile’, ‘crf_show_extra_profile_fields’ );

    function crf_show_extra_profile_fields( $user ) {
    ?>

    ID ) ); ?>

    <?php
    }

    • Anastis Sourgoutsidis says:

      It looks like you are checking for a registration_code, but you field is named year_of_birth.
      Please don’t post code as a comment. Use a gist instead.

Leave a Reply

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

Get access to all WordPress themes & plugins

24/7 Support Included. Join 115,000+ satisfied customers.

Pricing & Sign Up

30-day money-back guarantee. Not satisfied? Your money back, no questions asked.

Back to top