Execute plugin for specific user role(s) only

How can I have specific plugins only active for one specific user role (or potentially an array of user roles)?

Is there something I can add to my functions.php in the child theme to only use a specific plugin for a specific user role?

I have tried various answers from here and articles but nothing seems to offer what I need.

Update:

I’ve tried the below code (as a test) and it works in that if an admin accesses the site it disables the plugin, but once it’s disabled it stays disabled for everyone. It needs to asses the current user and activate or reactivate depending on their role.

add_filter( 'option_active_plugins', 'custom_plugin_load_filter' );
function custom_plugin_load_filter( $plugins ) {
    $user = wp_get_current_user();
    if ( in_array( 'administrator', (array) $user->roles ) ) {
        //unset( $plugins['additional-order-confirmation-email/additional-order-confirmation-email.php'] ); // change my-plugin-slug
         $key = array_search( 'additional-order-confirmation-email/additional-order-confirmation-email.php' , $plugins );
            if ( false !== $key ) {
                unset( $plugins[$key] );
            }

    }
    return $plugins;
}   

If I change it to !in_array it remains active for admin users (correct) but also for guests (incorrect).

2 Answers
2

It’s not a good idea to modify plugins if you can help it, as the plugin may be upated and you will lose your changes and need to redo them.

Fortunately, that is not necessary in this case anyway, as you can the filter active plugins option instead. You will need the plugin slug for this:

add_filter( 'option_active_plugins', 'custom_plugin_load_filter' );
function custom_plugin_load_filter( $plugins ) {
    $user = wp_get_current_user();
    if ( !in_array( 'sales_events', (array) $user->roles ) ) {
        unset( $plugins['my-plugin-slug'] ); // change my-plugin-slug
    }
    return $plugins;
}

Note as this will run on the plugins page also, it will probably prevent anyone without the role from disabling the plugin (as it will appear to be inactive to them.)

Leave a Comment