Correct Way to Hook jQuery Script in WordPress

I’ve got a WordPress site and have a .js file that I would like linked up so I can call the script. After much research, I’ve found this must be done with a hook in functions.php. I’ve tried all sorts of variations but cannot get the official method to work, but I have found a way that does work but just breaks the rest of the site in the process.

What am I doing wrong? I know about the get_stylesheet_directory_uri() & get_template_directory_uri() differences with parent and child themes but neither seem to make any difference.

Read More

Here’s the ‘official’ way that doesn’t work:

function add_jquery_script() {
  wp_enqueue_script(
    'my-script', // name your script so that you can attach other scripts and de-register, etc.
     get_stylesheet_directory_uri() . 'http://<site>.com/wp-content/themes/dt-the7/custom-scripts.js', // this is the location of your script file
     array('jquery') // this array lists the scripts upon which your script depends
  );
}

The ‘not recommended at all’ way that works but breaks the rest of the site:

function add_jquery_script() {
    echo '<script type="text/javascript" src="http://<site>/wp-content/themes/dt-the7/custom-scripts.js"></script>' . "n";
}
add_action('wp_head', 'add_jquery_script');

As always, any help much appreciated. Thanks guys

UPDATE

After echoing out get_stylesheet_directory_uri() I can see that my URL needs to be relative, which should now be as follows, however it still will not work.

function add_jquery_script() {
  wp_enqueue_script(
    'my-script', // name your script so that you can attach other scripts and de-register, etc.
     get_stylesheet_directory_uri() . '/custom-scripts.js', // this is the location of your script file
     array('jquery') // this array lists the scripts upon which your script depends
  );
}

Related posts

Leave a Reply

1 comment

  1. PHP

    You need to call the function add_jquery_script(); before it can be expect to output anything – pretty simple, easily forgotten.

    JQuery

    The script was breaking your code because of a reference error, var price definition should be moved inside the function so it is in the function’s scope.
    http://learn.jquery.com/javascript-101/scope/

    $(document).ready(function () {
        refresh();
        $('#bittrex-price').load(bittrexPrice);
    });
    
    function refresh() {
        var price = "[domain hidden]/realtime/bittrex-realtime.php";
        setTimeout(function (price) {
            $('#bittrex-price').fadeOut('slow').load(price, params).fadeIn('slow');
            $('#bittrex-vol').fadeOut('slow').load(price, params2).fadeIn('fast');
            refresh();
        }, 1000);
    }