set_user_role

Home » Hooks » set_user_role

The "set_user_role" hook is a WordPress action hook that is triggered when a user’s role is changed. It allows developers to perform custom actions or modify data when a user’s role is updated.

This hook is useful in scenarios where you need to add some additional functionality or perform certain tasks when a user’s role is changed. For example, you could use the "set_user_role" hook to send a notification email to the user when their role is updated, update specific user meta data based on the new role, or even log the role change for audit purposes.

Here’s an example usage of the "set_user_role" hook:

function custom_user_role_change( $user_id, $new_role, $old_role ) {
    // Perform custom actions or modifications here
    // For example, send a notification email to the user
    wp_mail( get_userdata( $user_id )->user_email, 'Role Update', 'Your role has been changed to ' . $new_role );

    // Update user meta data based on the new role
    update_user_meta( $user_id, 'last_role_change', current_time( 'timestamp' ) );
}
add_action( 'set_user_role', 'custom_user_role_change', 10, 3 );

In this example, we have created a custom function called "custom_user_role_change" that is hooked to the "set_user_role" action. This function accepts three parameters: $user_id, $new_role, and $old_role, which represent the ID of the user whose role is being changed, the new role, and the previous role, respectively.

Inside the function, we send a notification email to the user using the wp_mail() function and update the user’s "last_role_change" meta data with the current timestamp using the update_user_meta() function.

By utilizing the "set_user_role" hook, you can extend the functionality of WordPress and perform custom actions whenever a user’s role is updated.

Learn More on WordPress.org

WordPress snippets using the set_user_role hook

Register an account to save your snippets or go Pro to get more features.