Viewing 3 replies - 1 through 3 (of 3 total)
  • Moderator Jose Castaneda

    (@jcastaneda)

    THEME COFFEE MONKEY

    One of the few reasons it is recommended to bundle scripts. ??

    What’s really cool is that WordPress has jQuery bundled. The key thing is to enqueue it.

    https://developer.www.ads-software.com/reference/functions/wp_enqueue_script/
    https://codex.www.ads-software.com/Function_Reference/wp_enqueue_script

    Something quick to load both jquery and bootstrap:

    /* enqueueing the right files */
    add_action( 'wp_enqueue_scripts', 'my_enqueue_method' );
    function my_enqueue_method(){
       wp_enqueue_script( 'bootstrap-js', get_template_directory() . '/js/bootstrap.js', array( 'jquery' ), '', true );
    }

    Thread Starter rawadmerhi

    (@rawadmerhi)

    Jose I’m brand new to WordPress, would you mind explaining what that code does, and what was the problem with my other code?

    Moderator Jose Castaneda

    (@jcastaneda)

    THEME COFFEE MONKEY

    Be happy to!

    add_action( 'wp_enqueue_scripts', 'my_enqueue_method', 10 );

    Uses a callback my_enqueue_method to load the scripts. The wp_enqueue_scripts part is what, to a degree, holds -our houses- all scripts. ( It also handles stylesheets ). Now, when you add an action to it what you are telling WordPress is, “get this in line to print.” The way WordPress does a lot of things is by using action, and filter hooks. It’s really cool because that way you can taylor it to suit your different needs. ??

    function my_enqueue_method(){
       wp_enqueue_script( 'bootstrap-js', get_template_directory_uri() . '/js/bootstrap.js', array( 'jquery' ), '', true );
    }

    Is the callback function used to get the file(s) ready for printing onto the HTML document. Each $arg has a different meaning and purpose.

    // The first argument passed is the name of the script,
    // the second argument is the location of the script,
    // the third argument is an array of dependencies,
    // the fourth argument is the version of the script to enqueue,
    // the fifth argument is whether or not to load it in the footer
    wp_enqueue_script( 'bootstrap-js', get_template_directory_uri() . '/js/bootstrap.js', array( 'jquery' ), '', false );

    I can only guess why that worked. As I mentioned, using local files is a lot easier rather than using remote files ( CDN hosted ). Odds are the jQuery script isn’t fully loaded when you call it in the footer?

    ps. I realized it should be get_template_directory_uri() as I was typing it and that’s not what I originally used. ( My bad ).

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘JQuery Won't work on WordPress Theme’ is closed to new replies.