There are a few different ways to conditionally deactivate or activate a plugin based on the logged-in user’s role in WordPress. One way is to use the is_user_logged_in()
function, along with wp_get_current_user()
to check the user’s role, and then use the deactivate_plugins()
and activate_plugins()
functions to deactivate or activate the plugin as needed.
Here’s an example of how you might use these functions to deactivate a plugin called “Example Plugin” for users with the role of “subscriber”:
if ( is_user_logged_in() ) {
$current_user = wp_get_current_user();
if ( in_array( 'subscriber', (array) $current_user->roles ) ) {
deactivate_plugins( 'example-plugin/example-plugin.php' );
}
}
Alternatively, you could use current_user_can()
function to check if a user has a specific capability.
if ( is_user_logged_in() && ! current_user_can( 'edit_posts' ) ) {
deactivate_plugins( 'example-plugin/example-plugin.php' );
}
You can also use activate_plugins()
to activate the plugin for certain users.
It is important to note that if you use the above code, it will only work once. If you need to deactivate a plugin based on user roles, you need to use a plugin like ‘User Role Editor’ and then you will be able to assign certain role the capability to use certain plugin.
Another approach you can use is to create a simple plugin which will handle all the actions related to plugin activation/deactivation based on user roles, this way you can keep your code in a more organized manner.