Using WordPress ‘edit_user()’ PHP function

The edit_user() WordPress PHP function is utilized on user-edit.php and profile.php to manage and alter user options, passwords, and other settings based on the contents of $_POST.

Usage

A typical use of the edit_user() function might look like this:

$user_id = 123; // Replace 123 with the ID of the user you want to edit
edit_user($user_id);

Parameters

  • $user_id (int, optional): The ID of the user you want to edit.

More information

See WordPress Developer Resources: edit_user()
Note: Always make sure to validate and sanitize the $_POST data before using the edit_user() function to prevent security issues.

Examples

Changing User Password

In this example, we will change the password of a user.

// Assume we already have a user_id and a new password
$new_password = 'new_password';
wp_set_password($new_password, $user_id);

Updating User Email

Here, we’ll update a user’s email address.

// We have user_id and the new email
$new_email = '[email protected]';
wp_update_user(array('ID' => $user_id, 'user_email' => $new_email));

Updating User Role

In this case, we’ll change a user’s role.

// We have user_id and the new role
$new_role = 'editor';
$user = new WP_User($user_id);
$user->set_role($new_role);

Deleting a User

Here, we’ll delete a user.

// We have the user_id
wp_delete_user($user_id);

Adding Meta Data for a User

Finally, we’ll add meta data for a user.

// We have user_id and new meta data
$meta_key = 'extra_info';
$meta_value = 'This user loves WordPress.';
add_user_meta($user_id, $meta_key, $meta_value);

Each example demonstrates a different operation we can perform on a user with the edit_user() function. Please replace the example values with actual data for your use case.