How to create a simple plugin to handle activation/deactivation

Photo of author
Written By geekerhub

Experienced WordPress developer with over 10 years of experience working with the platform

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:

  1. Create a new directory in the wp-content/plugins folder of your WordPress installation, and name it something like “user-role-plugin-control”.
  2. Inside this directory, create a new file called “user-role-plugin-control.php”. This will be the main plugin file.
  3. Open “user-role-plugin-control.php” in a text editor and add the following code at the top, which will create the plugin header:
Copy Code
 * Plugin Name: User Role Plugin Control
 * Plugin URI:
 * Description: A plugin to control plugin activation/deactivation based on user roles.
 * Version:     1.0
 * Author:      John Doe
 * Author URI:
 * License:     GPL2
 * License URI:
  1. 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:
Copy Code
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' );
  1. 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.
  2. 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.

Leave a Comment