Ready to Transform Your Online Presence? Let's Get Started!

WordPress – create a new usermeta field for users

Do you want to add a custom meta field to add custom data for users in create user page, edit the user page and show the user page?

There is a way to do this using WordPress Hooks like user_new_form, edit_user_profile, and show_user_profile. These hooks will show your field on create user screen, edit user screen, and show user screen.

You have to add the given code in your currently active theme’s functions.php file..

<?php
add_action('show_user_profile', 'my_user_profile_edit_action'); // editing your own profile
add_action('edit_user_profile', 'my_user_profile_edit_action'); // editing another user
add_action('user_new_form', 'my_user_profile_edit_action'); // creating a new user
function my_user_profile_edit_action($user) {
	$s_branch = get_user_meta($user->ID, 'ag_bm_branch', true);
?>
  <h3>Select Branch <small>( For Branch Manager Only )</small></h3>
  <label for="ag_bm_branch">
    <select name="ag_bm_branch" id="ag_bm_branch">
        <option value="">Select Branch</option>
	<option value="Branch 1">Branch 1</option>
	<option value="Branch 2">Branch 2</option>
    </select>
  </label>
<?php 
}
?>

We have to save or update this meta field data to the database using other hooks like personal_options_update, edit_user_profile_update, and user_register.

function my_user_profile_edit_action_save($userId) {
   update_user_meta($userId, 'ag_bm_branch', $_REQUEST['ag_bm_branch']);
}
add_action('personal_options_update', 'my_user_profile_edit_action_save');
add_action('edit_user_profile_update', 'my_user_profile_edit_action_save');
add_action('user_register', 'my_user_profile_edit_action_save');

I hope this WordPress Tutorial will help you. Thanks