If you deactivate a plugin, the change is stored in database, so in all subsequent access the plugin is deactivated, no matter the device used to access the site.
Filtering the option
Active plugin in WordPress are retrieved using wp_get_active_and_valid_plugins()
function.
It uses the option "active_plugins"
to get the currently active plugin. All options in WordPress can be filtered using the "option_{$option}"
filter hook, that in this case is "option_active_plugins"
.
Acting early
You may think to use a plugin to filter that option, but the problem is that is possible that the plugins(s) you want to exclude are loaded before your plugin, because you can’t never be sure you plugin is loaded for first.
The solution is to use a MU plugin for the scope.
Too early issue
MU plugins run very early in WordPress, that gives you the possibity to filter the "option_active_plugins"
option.
Another issue is that MU plugins load very early, even before the file wp-includes/vars.php
that contain the function wp_is_mobile()
is loaded, so if you use that function inside a MU plugin you get a fatal error.
Load the file “manually” is not an option, because WordPress will load that file using require
and not require_once
, so if you load the file, when WordPress load it again you get a fatal error for function already defined.
The only solution is write again wp_is_mobile()
, just coping from core and using a different name.
Let’s code
Create PHP file and save in wp-content/mu-plugins
folder.
First of all write there a function that returns all the plugin you want to disable for mobile devices:
function my_non_mobile_plugins() {
return array(
// an array of all the plugins you want to exclude for mobile
'plugin-folder/plugin-file.php',
'another-plugin-folder/another-plugin-file.php',
'no-folder-plugin-file.php'
);
}
After that write a clone of wp_is_mobile()
function, with another name:
function my_is_mobile() {
$is_mobile = false;
if ( strpos($_SERVER['HTTP_USER_AGENT'], 'Mobile') !== false
|| strpos($_SERVER['HTTP_USER_AGENT'], 'Android') !== false
|| strpos($_SERVER['HTTP_USER_AGENT'], 'Silk/') !== false
|| strpos($_SERVER['HTTP_USER_AGENT'], 'Kindle') !== false
|| strpos($_SERVER['HTTP_USER_AGENT'], 'BlackBerry') !== false
|| strpos($_SERVER['HTTP_USER_AGENT'], 'Opera Mini') !== false
|| strpos($_SERVER['HTTP_USER_AGENT'], 'Opera Mobi') !== false
) {
$is_mobile = true;
}
return $is_mobile;
}
Finally, filter 'option_active_plugins'
making use of previous function to check if remove plugins or not
add_filter( 'option_active_plugins', 'my_disable_plugins_for_mobiles' );
function my_disable_plugins_for_mobiles( $plugins ) {
if ( ! my_is_mobile() ) {
return $plugins; // for non-mobile device do nothing
}
$not_allowed = my_non_mobile_plugins(); // get non allowed plugins
return array_values( array_diff( $plugins, $not_allowed ) );
}