Creating a simple plugin to handle activation/deactivation Plugin based on user roles is relatively straightforward. Here’s an example of how you might go about doing this:
- Create a new directory in the
wp-content/plugins
folder of your WordPress installation, and name it something like “user-role-plugin-control”. - Inside this directory, create a new file called “user-role-plugin-control.php”. This will be the main plugin file.
- Open “user-role-plugin-control.php” in a text editor and add the following code at the top, which will create the plugin header:
/**
* Plugin Name: User Role Plugin Control
* Plugin URI: https://example.com/
* Description: A plugin to control plugin activation/deactivation based on user roles.
* Version: 1.0
* Author: John Doe
* Author URI: https://example.com/
* License: GPL2
* License URI: https://www.gnu.org/licenses/gpl-2.0.html
*/
- Next, we’ll add the code to check the user’s role and deactivate or activate the plugins as necessary. Here’s an example of how you might do this:
function user_role_plugin_control() {
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' );
} elseif ( in_array( 'administrator', (array) $current_user->roles ) ) {
activate_plugins( 'example-plugin/example-plugin.php' );
}
}
}
add_action( 'init', 'user_role_plugin_control' );
- In the above code, we are deactivating ‘example-plugin/example-plugin.php’ for the subscribers and activating it for the administrators, this can be modified as per your requirement.
- Finally, you’ll need to zip the plugin directory and upload it to your WordPress site via the plugin installer or by ftp. Once it’s uploaded, you can activate the plugin from the WordPress admin area, and it will begin controlling the activation/deactivation Plugin based on user roles.
Note that, the code provided is an example, you will have to customize it according to your need. Also, you should check the capability of the user instead of checking the role by using current_user_can()
function as stated earlier, and this way, you can handle even the custom roles.