Exciting News! Flipper Code is now WePlugins! Same commitment to excellence, brand new identity.

How to use add_user_role action in WordPress

Sandeep Kumar Mishra
Sandeep Kumar Mishra
April 11, 2023
5 minutes read

Working with WordPress hooks can be quite rewarding! Today, we’re diving into the add_user_role action, which fires immediately after a user is assigned a new role. Whether you’re customizing your theme or building a custom plugin, understanding this hook can add some serious functionality to your site.

To use the add_user_role action, you’ll want to register it with add_action. Many developers, like us at WePlugins, prefer creating custom plugins for hooks to ensure nothing breaks with theme updates. Below are some live examples of how to work with this hook.

Example 1: Add User Role Action

Here’s how you can execute some code whenever a user is assigned a new role.

    function weplugins_execute_on_add_user_role_event($user_id, $role){
       // Write code here to handle the action when a user's role is updated.
    }
    // Add the action
    add_action( "add_user_role", "weplugins_execute_on_add_user_role_event" , 10, 2);
    

Example 2: Remove User Role Action

If you need to remove a registered hook, the example below will guide you.

    remove_action( "add_user_role", "weplugins_execute_on_add_user_role_event", 10, 2 );
    

Ensure you provide the same callback function name, priority, and number of arguments when removing the hook.

Example 3: Custom Functionality

Integrate additional custom functionality according to your website’s requirements using the parameters received in the function arguments.

    function weplugins_custom_user_role_action($user_id, $role){
       // Custom functionality here
    }
    add_action( "add_user_role", "weplugins_custom_user_role_action" , 10, 2);
    

Parameters: The add_user_role hook requires two parameters: $user_id (int) for the user ID and $role (string) for the new role.

Access Premium WordPress Plugins

Contact Us

If you need any customization or are facing issues with this hook, feel free to Contact Us. We’re here to help!

Sandeep Kumar Mishra

Sandeep Kumar Mishra

Sandeep Kumar Mishra writes about WordPress and Artificial Intelligence, offering tips and guides to help you master your website and stay updated with the latest tech trends.

Explore the latest in WordPress

Trying to stay on top of it all? Get the best tools, resources and inspiration sent to your inbox every Wednesday.