How to add custom field in User form on Add / Edit.

By : Admin  |  Updated On : 2 days ago

How to add custom field in User form on Add / Edit.

In wordpress create custom field in user form by using ACF (Advanced Custom Field) plugin and also by using custom php code without using any plugin.

I will let you know step by step this process, First know how to do this with ACF Plugin.

1. Open your wordpress admin panel.

2. Install ACF (Advanced Custom Field) Plugin.

3. As per below image click on the Add new of Custom Field.

Custom field add new button

4. Now create a field as given in the below image and do not forget to choose the User Form in location.

wordpress create custom field5. Now your custom field is created and attached to the user form. You can check in your user form in both add and edit form. Here I have created a checkbox as external user and it is available in user form, you can check this in the below image.

wordpress user add-edit form

 

Above process is done using ACF Plugin. Now let you know step by step how to do the same using custom php code in functions.php of theme.

1. First of all call below hooks with add_action function.

add_action('show_user_profile', 'isExternalUser');
add_action('edit_user_profile', 'isExternalUser');
add_action('user_new_form', 'isExternalUser');

2. Now create the isExternalUser hook function.

function isExternalUser($user) {

    $checked = esc_attr(get_the_author_meta('is_external_user', $user->ID)) == 1 ? ' checked ' : ' ';

    echo '<table class="form-table">
            <tr>
                <th><label for="columnist">Is External User</label></th>
                <td>
                    <input' . $checked . 'type="checkbox" name="is_external_user" id="is_external_user" value="1" class="checkbox double" />
                    <span class="description">Check if user is External.</span>
                </td>
            </tr>
        </table>';
}

3. Again call below hooks with add_action function.

add_action('personal_options_update', 'update_user_external');
add_action('edit_user_profile_update', 'update_user_external');
add_action('user_register', 'update_user_external');

4. Now create update_user_external hook function.

function update_user_external($user_id) {

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

    $columnistValue = 0;
    if (isset($_POST['is_external_user'])) {
        $columnistValue = 1;
    }

    update_usermeta($user_id, 'is_external_user', esc_attr($columnistValue));
}

Now your custom field with custom php code is created. You can check in your add/edit user form. Also look into the below image which I have shared.

custom php code for custom field

 

 

All done !! 

Please comment if you have any query.