How to add new custom field in default add user form through plugin

It is possible. For that we will use 4 hooks (actions): show_user_profile, edit_user_profile, personal_options_update, edit_user_profile_update.

Here is the example how to add extra field to user in WordPress.

Adding user info fields function

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

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

    <table class="form-table">
    <tr>
        <th><label for="user_img_path_image"><?php _e("Image path"); ?></label></th>
        <td>
            <input type="text" name="user_img_path_image" id="user_img_path_image" value="<?php echo esc_attr( get_the_author_meta( 'user_img_path_image', $user->ID ) ); ?>" class="regular-text" /><br />
            <span class="description"><?php _e("Path to country image."); ?></span>
        </td>
    </tr>
    <tr>
        <th><label for="user_country_field"><?php _e("Country field"); ?></label></th>
        <td>
            <input type="text" name="user_country_field" id="user_country_field" value="<?php echo esc_attr( get_the_author_meta( 'user_country_field', $user->ID ) ); ?>" class="regular-text" /><br />
            <span class="description"><?php _e(""); ?></span>
        </td>
    </tr>

    </table>
<?php }

Here is the extra code for save and edit function

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, 'user_img_path_image', $_POST['user_img_path_image'] );
    update_user_meta( $user_id, 'user_country_field', $_POST['user_country_field'] );

}
// end - Add user info fields

Just copy and paste this code in your plugin or function.php and you must see new 2 fields in WordPress backend user editing/adding page.

For extracting your date in frontend use this code:

$user_facebook_id_acc = get_the_author_meta( 'user_facebook_id_acc', $current_user_data->ID );

Leave a Comment