Execute a function when admin changes the user role

The question:

How can I execute a function, when admin changes the user role of a user?

I have two user roles: one is agent and the other one is client .

My need is that when admin changes the user role of client to agent, I need to execute a specific function.

In this function I need to get the all content and meta fields of user by getting the user id.

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

You can use the set_user_role hook, that will only fire when the user role changes:

add_action( 'set_user_role', function( $user_id, $role, $old_roles ) 
{
    // Your code ...

}, 10, 3 );

If you want to restrict this to a profile update, you can use:

add_action( 'set_user_role', function( $user_id ) 
{
    add_action( 'profile_update', function( $user_id )
    {
        // Your code here ...            
    } );

} );


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment