0

I am trying to enable a plugin only for mobile and I have consulted this thread: Deactivate plugins only for mobile devices

I have made some changes to the last function as I want to enable only for mobile, while the thread suggest how to disable to mobile.

I don't know how specify the plugin that I want to specify, so I include 2 files. This is in a folder in my wp-content/ plugins/name-of-plugin, where there are an index.php file and a name-of-plugin.php file.

This is my code, saved in a my-code.php file, places on mu-plugins of wordpress. Unfrotunately, it doesn't work. Any help how to fix this?

 <?php

/**
 * Plugin Name: My mobile enabler
 */

function my_non_mobile_plugins() {
  return array(

    // i am not sure how specifiy the plugin I want to disable. I have added these two lines

    '/name-of-folder-plugin/plugin-name.php',
    '/name-of-folder-plugin/index.php'
  );
}

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;
}


add_filter( 'option_active_plugins', 'my_disable_plugins_for_mobiles' );

function my_disable_plugins_for_mobiles( $plugins ) {

  if ( ! my_is_mobile() ) {
  $not_allowed = my_non_mobile_plugins(); // get non allowed plugins

  return array_values( array_diff( $plugins, $not_allowed ) );
    
  }

return $plugins; // for mobile device do nothing

}
3
  • 3
    if it's your plugin then why disable it on mobiles? Just detect if it's a mobile and return early, there's no need to disable the plugin, deactivating a plugin per page load is not a good approach. Especially when you can open a browser sized to behave like a mobile, and you can unfold a mobile to take up a tablet sized UI, detecting mobiles will be unreliable ( and fundamentally incompatible with page caching plugins and CDNs such as cloudflare )
    – Tom J Nowell
    Commented Aug 20, 2021 at 14:11
  • No this isn't my plugin, so that's why I want to enable for mobile. Commented Aug 20, 2021 at 23:50
  • what problem are you fixing by doing this?
    – Tom J Nowell
    Commented Aug 21, 2021 at 16:25

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.