Wordpress - How I prevent a plugin to be loaded when doing WP-CLI?

You can use the skip-plugins option in WP-CLI to not load individual plugins when using WP-CLI.

You can either use it in command like this:

wp user list --skip-plugins=my-plugin

Or you can add this to your wp-cli.yml file:

skip-plugins:
- my-plugin

One of the first things WordPress does to load plugins is get the active plugins as saved in the database:

$active_plugins = (array) get_option( 'active_plugins', array() );

Since it uses get_option() we can use the option_active_plugins filter to modify the list of active plugins on the fly.

function wpse_301282_disable_plugin( $active_plugins ) {
    if ( defined( 'WP_CLI' ) && WP_CLI ) {
        $key = array_search( 'gravityforms/gravityforms.php', $active_plugins );

        if ( $key ) {
            unset( $active_plugins[$key] );
        }
    }

    return $active_plugins;
}
add_filter( 'option_active_plugins', 'wpse_301282_disable_plugin' );

Just replace gravityforms/gravityforms.php with the directory and filename of the plugin you want to disable.

The problem here is that we are trying to affect the loading of plugins, so we can't do that from within a plugin, because it's too late. In the theme would also be too late.

Thankfully WordPress has "Must Use Plugins" these are plugins you can add that are loaded before and separately to regular plugins, and do not appear in the regular plugins list.

All you need to do to add this code to a Must Use Plugin is to create a wp-content/mu-plugins directory (if it doesn't already exist) and create a PHP file (it can be called anything) with that code in it. You don't need a plugin header or anything else.

Now that code will be loaded before all other plugins when WordPress loads. Since our filter is in place, when WordPress gets the list of active plugins to load the plugin you want to disable will be filtered out of that list if WP-CLI is active.

Tags:

Plugins

Wp Cli