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

I currently use this code in the main plugins file itself. But that plugin is not my own so I would prefer to be able to upgrade it normally without every time adding this code.

if ( defined( 'WP_CLI' ) && WP_CLI ) {

I need to do this because this plugin produces errors and stops wp-cli to execute correctly so I can’t just disable the plugin with wp-cli, do my tasks and re-enable it.

Is there a way I can do something like if x then do not load plugin file x from within a mu-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.

Leave a Comment