1

I have a script I want to place in my site's footer. It's not actually a file, just a single line of code (the script source is located at an external URL). So my question is, should I enqueue the script or just copy and paste it into the footer?

1
  • 1
    In this case it may not matter. Personally, I would enqueue it in the event that the script depends on another library, you can then set the dependencies for the script without worrying if it will load in the wrong order.
    – disinfor
    Nov 8, 2017 at 2:14

2 Answers 2

1

If you want to output a single line of javascript, you might not need to put it in a js file and go through enqueuing it and stuff. Simply output it by using the wp_footer() action hook:

add_action('wp_footer','print_my_script');
function print_my_script(){
    echo '<script> // Your script here </script>';
}

However, this is good just for small scripts. For larger script and js files, use wp_enqueue_script() instead.

2

See wp_enqueue_script() and the $in_footer parameter it supports. Here's an example of how you'd do this from the functions.php file for your theme. Note the last argument is true, which inserts the script into the footer.

<?php
add_action( 'wp_enqueue_scripts', function() {
    wp_enqueue_script( 'my-script', '/path/to/script.js', [], null, true );
} );
4
  • So, to use the wp_enqueue_script function I would need to either first register the script using wp_register_script() or link to it in the wp_enqueue_script function? In that case the answer given by @Jack Johansson might be the better option.
    – jrcollins
    Nov 8, 2017 at 4:29
  • You don't need to register it first, that's just a formality for the sake of plugins. If it's just a file for your site, you can literally copy/paste the example snippet and change the first two parameters; i.e., change my-script to a handle that matches your script, and the second parameter should be a URL or absolute file path leading to the script.
    – jaswrks
    Nov 8, 2017 at 4:52
  • To clarify, if you 'register' a script, it allows that script to be enqueued and dequeued later; e.g., by a theme or by plugins. So it's better, yes. However, if this is for a site-specific script there's really no need. Just enqueue.
    – jaswrks
    Nov 8, 2017 at 4:54
  • The $src variable in the wp_enqueue_script function is optional so if you don't link to the script in the wp_enqueue_script function you would need to have previously registered the script. As mentioned in my question, the script is just a single line of code so I'm thinking the answer given by @Jack Johansson might make more sense in this context.
    – jrcollins
    Nov 8, 2017 at 6:01

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.