4

I'm trying to make load a simple javascript code on wordpress just on mobile in header.

I've tried plugins and to code but It seems not within my reach and need help :D

Ciao!

Jung dev
  • 51
  • 1
  • 2

3 Answers3

6
function custom_load_scripts() { 
   // Load if not mobile 
   if ( ! wp_is_mobile() ) { 
      // Example script 
      wp_enqueue_script( 'script-name',get_template_directory_uri() . '/js/example.js', array (), '1.0.0', true ); 
      } 
}

add_action( 'wp_enqueue_scripts', 'custom_load_scripts' );
Samvel Aleqsanyan
  • 2,812
  • 4
  • 20
  • 28
4

Other answers have suggested using the WordPress function wp_is_mobile() when enqueuing a script. Be very careful doing this. If you use caching plugins or if your host caches PHP requests, this could make this method useless.

Instead, I would recommend loading the JavaScript file and testing to see if the browser is mobile or not based on the screen size of the device using JavaScript.

Here is an example (uses jQuery):

$( document ).ready(function() {      
    var isMobile = window.matchMedia("only screen and (max-width: 760px)");

    if (isMobile.matches) {
        //Add your script that should run on mobile here
    }
 });
Marc
  • 4,661
  • 3
  • 40
  • 62
0

You shouldn't be adding JS (or CSS) files directly to your header.php or footer.php files.

What you can do instead is enqueue and dequeue scripts and styles use the wp_enqueue_scripts hook.

Inside a function on that hook, you'll add scripts using the wp_enqueue_script() function. Setting the 5th argument to true will put the code in the header.

You'll note the 3rd argument is an array, that's an array of scripts that your code is dependent on, such as if your code relies on jQuery, you could change that to array( 'jquery' )

Lastly, WordPress has a function to detect mobile devices that works relatively well, conveniently called wp_is_mobile().

So we can just check if that returns true before we enqueue our script.

Place this code in your functions.php file, of course after replacing the URL with the URL to your script.

add_action( 'wp_enqueue_scripts', 'jung_mobile_only_js');
function jung_mobile_only_js(){
    if( wp_is_mobile() ){
        wp_enqueue_script( 'jung-mobile-only-js', 'URL_TO_YOUR_JS_FILE_HERE', array(), '1.0', true );
    }
}
Xhynk
  • 13,513
  • 8
  • 32
  • 69