1

Basically I am running a JavaScript on one of my pages but I don't want it displayed on mobiles. Is this doable in PHP? I've added an enqueue function in my WordPress child theme as per the below:

function load_js_assets() {
if( is_page( 1509 ) ) {
    wp_enqueue_script('custom-script', 'https://cdn.jsdelivr.net/particles.js/2.0.0/particles.min.js', array('jquery'), '', false);
    wp_enqueue_script('custom-script2', 'https://unidigital.tech/wp-content/themes/picostrap-child/particles.js?ver=5.6', array('jquery'), false, true);
    
} 

}

But I haven't managed to succesfully add a condition to only run the JS on big screens. Can anyone help please?

  • Are you trying to detect the screen size using only PHP? – terrymorse Jan 10 '21 at 23:52
  • yes, I could just use CSS to not display the JS but it would still run in the background - which I would like to avoid – Kevin Rawls Jan 10 '21 at 23:57
  • Try to use [Mobile Detect](https://github.com/serbanghita/Mobile-Detect) to determine the user device – Illya Jan 11 '21 at 00:02
  • i dont know too much about wordpress, but maybe you can try detect screen size with javascript first, then load javascript like a example.com/js/xxx.php?screensize=1509 – Lexa Vey Jan 11 '21 at 00:04

3 Answers3

0

Use the following snippet to enqueue javascript only on non-mobile devices.

  

    //Identify is request is coming from a mobile browser.
    function isMobileDevice() { 
        return preg_match("/(android|avantgo|blackberry|bolt|boost|cricket|docomo 
    |fone|hiptop|mini|mobi|palm|phone|pie|tablet|up\.browser|up\.link|webos|wos)/i" 
    , $_SERVER["HTTP_USER_AGENT"]); 
    } 
    
    function load_js_assets() {
        if( is_page( 1509 ) && !isMobileDevice()) {
            wp_enqueue_script('custom-script', 'https://cdn.jsdelivr.net/particles.js/2.0.0/particles.min.js', array('jquery'), '', false);
            wp_enqueue_script('custom-script2', 'https://unidigital.tech/wp-content/themes/picostrap-child/particles.js?ver=5.6', array('jquery'), false, true);
        }
    }

Vikas Wani
  • 26
  • 3
0

The simple answer is no, you cannot reliably detect the platform with PHP. There are two reasons:

  1. PHP runs on the server and has no business on the client-side. There are some hacks using the browser string, however those are platform-dependent and easy to spoof.

  2. The line between mobile and not mobile devices is blurry. See answers and comments to this question

The best approach is to design your website in such a way that you do not need to make these checks at all.

Eriks Klotins
  • 3,546
  • 1
  • 8
  • 23
-1

look at the side of the css are things possible easily

michael
  • 15
  • 5