WordPress how do add a field on the Users profile?

90 Likes Comment

Need to use the show_user_profileedit_user_profilepersonal_options_update, and edit_user_profile_update hooks

You can use the following code for adding additional fields in User section

Code for adding extra fields in Edit User Section:

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

function extra_user_profile_fields($user) { ?>
    <h3><?php _e("Extra profile information", "blank"); ?></h3>

    <table class="form-table">
        <th><label for="address"><?php _e("Address"); ?></label></th>
            <?php $v = esc_attr(get_the_author_meta('address', $user->ID)); ?>
            <input type="text" name="address" id="address" value="<?= $v ?>" class="regular-text" /><br />
            <span class="description"><?php _e("Your address."); ?></span>
        <th><label for="city"><?php _e("City"); ?></label></th>
            <?php $v = esc_attr(get_the_author_meta('city', $user->ID)); ?>
            <input type="text" name="city" id="city" value="<?= $v ?>" class="regular-text" /><br />
            <span class="description"><?php _e("Your city."); ?></span>
    <th><label for="postalcode"><?php _e("Postal Code"); ?></label></th>
            <?php $v = esc_attr( get_the_author_meta('postalcode', $user->ID)); ?>
            <input type="text" name="postalcode" id="postalcode" value="<?= $v ?>" class="regular-text" /><br />
            <span class="description"><?php _e("Your postal code."); ?></span>
<?php }

Code for saving extra fields details in database:

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

function save_extra_user_profile_fields($user_id) {
    if (!current_user_can('edit_user', $user_id)) { 
        return false; 
    update_user_meta($user_id, 'address', $_POST['address']);
    update_user_meta($user_id, 'city', $_POST['city']);
    update_user_meta($user_id, 'postalcode', $_POST['postalcode']);

Source: https://wordpress.stackexchange.com/questions/214719/how-do-i-add-a-field-on-the-users-profile-for-example-country-age-etc

You might like

About the Author: Oleksandr Sovenko

Leave a Reply

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