Disable specified plugins except for certain pages - enhanced with caching.
In May last year I wrote code to disable plugins except for specified urls primarily to reduce the load that Contact Form 7 was placing on a site. Someone commented to recommend caching the list of permitted plugins. I have rewritten the code as a PHP class to do this.
Having come from a procedural programming background I rarely write OOP code though encapsulation has been very useful when I have done so. I used that here to cache the list of permitted plugins. For flexibility I also changed how the url is examined.
Search Change
I changed from array_search() to compare the permitted urls with the current url to a strpos() check of each permitted one individually. This change allows the Contact Form 7 REST API url through – it uses a url with the contact form ID. I decided against a regular expression in the permitted urls as regexs are often hard to read and understand. The strpos() check is that the url starts with the permitted url.
I also moved the is_admin() check outside the filter function. Now the filter function is not added if in the admin area.
As before, the plugin must be put in the wp-content/mu-plugins directory as it must run before regular plugins are loaded.
Thank you for sharing. I have a front end dashboard for our logged in users and I would like to disable just one plugin when visitors view the /dashboard/…. url. How can I use this code to do that? Thank you
I should write a post about disabling a plugin for one url. Someone else asked me about this a few months ago and I modified the code for that. https://gist.github.com/damiencarbery/2dd9b5ee828395ee1aea774b09c7e13b#file-disable-plugins-for-specified-urls-php
You will need to edit line 42:
'plugindir/pluginfile.php' => array( '/dashboard/' ),
to change ‘plugindir/pluginfile’ to match those of the plugin you want to disable. For example, for Contact Form 7 the line would be:'contact-form-7/wp-contact-form-7.php' => array('dashboard'),
Then upload the file into wp-content/mu-plugins directory.
Hi Damien. Thanks a lot for this. The current array for disable_plugins is Plugin Name => Urls. What if I need to disable multiple plugins for one Url?
@BT -To disable multiple plugins list each one and add the same url. Here we disable 3 plugins for /same-url/
'contact-form-7/wp-contact-form-7.php' => array( '/contact/', '/same-url/' ), 'advanced-custom-fields-pro/acf.php' => array( '/page-one/', '/same-url/', ), 'query-monitor/query-monitor.php' => array( '/same-url/' ),
Hello, thank you for sharing this awesome code. But it is possible to integrate this code with a specific post_type? For exemple, I want to disable the plugin X on all the posts, but not on pages.
@Hehe – I modified the code to check the post type but it did not work. The get_post_type() and is_single() and similar functions do not return values until *after* plugins are loaded. So, I do not think that it is possible.