Is it possible to dynamically “disable” a plugin with a condition determined by some visitor attributes? Like the presence of a cookie? Of course without changing the plugin code!
Recently I faced this problem: a rather weight plugin that integrates a chat (and more) in a WP site was make the site itself too slow. And the chat is not used but by few of the site visitors.
The best option would be a way to “enable” the chat on visitor demand, for example tapping on an icon and only after that actually load the chat plugin.
The site is diariogravidanza.it, it a very clean and light site (less than 40 pages) which the client want to keep quick as possible without sacrifice some cool features appreciated only by a small group of visitors.
Loading dynamically a plugin is not exactly easy, apparently, but diving deep in the wp-settings.php
file an idea came to my mind: to use the must use plugins.
So the requirements:
- The chat plugin must not be loaded by default
- If the vistors has the “chat” cookie the plugin can be loaded
- If the chat cookie is missing a “chat” icon should be shown and when tapped the cookie set and the page reloaded
Checking the WP load sequence inside the wp-settings.php
file, we can note that all must use plugins (every single file stored inside the wp-content/mu-plugins
folder) are loaded before regular plugins.
Then, regular plugins are loaded from a list store in a specific option, the active_plugins
option. This option is nothing than an array of strings where each entry is plugin main file (for example newsletter/plugin.php
).
You already got it: if we can temporary remove a plugin reference from that option we can block the plugin loading (on site fronted, of course).
Let assume the plugin we do not want to load is myplugin/plugin.php
. We can create a single file inside the wp-content/mu-plugins
folder named, just an example, load-or-not.php
. You can add some headers in that file, but it’s not required and WP will list it on its plugins page.
The code we need to add to load-or-not.php
file could resemble to this one:
<?php // Do nothing is we're in the admin side if (is_admin()) return; // Our not loading condition: the absence of the chat cookie (but can be anything else) if (!isset($_COOKIE['chat'])) { // Intercept the option "active_plugins" content add_filter('option_active_plugins', function($plugins) { $i = array_search('myplugin/plugin.php', $plugins); if ($i !== false) { unset($plugins[$i]); } return $plugins; }); }
As you can see the code is rather simple. When WP loads the option containing the list of active plugin, we intercept it, search for our plugin slug and remove it. The plugin won’t be deactivate, just not loaded!
The condition on this example is the presence of a cookie, but you can do everything else. Just note that, at this time, the user is still not initialized to the is_user_logged_in()
function probably won’t work.