User profile custom field

Here is an example using a field called my_field. The value is successfully saved and displayed:

// Declaring the form fields
add_action( 'show_user_profile', 'wpse_show_my_fields' );
add_action( 'edit_user_profile', 'wpse_show_my_fields' );
add_action( 'user_new_form',     'wpse_show_my_fields' );
function wpse_show_my_fields( $user ) {
    $fetched_field = get_user_meta( $user->ID, 'my_field', true ); ?>
    <tr class="form-field">
        <th scope="row"><label for="my_field"><?php _e( 'Field Name', 'text-domain' ) ?> </label></th>
        <td>
            <input name="my_field" type="text" id="my_field" value="<?php echo esc_attr( $fetched_field ); ?>">
        </td>
    </tr><?php
}

// Saving my form fields
add_action( 'personal_options_update',  'wpse_save_my_form_fields' );
add_action( 'edit_user_profile_update', 'wpse_save_my_form_fields' );
add_action( 'user_register',            'wpse_save_my_form_fields' );
function wpse_save_my_form_fields( $user_id ) {
    update_user_meta( $user_id, 'my_field', $_POST['my_field'] );
}

add_action( 'edit_user_created_user', 'wpse_edit_user_created_user', 10, 2 ); // for user-new.php page new user addition
function wpse_edit_user_created_user( $user_id, $notify ) {
    $meta = get_user_meta( $user_id, 'my_field', true );
}

Leave a Comment