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?
2 Answers
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.
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 );
} );
-
So, to use the
wp_enqueue_script
function I would need to either first register the script usingwp_register_script()
or link to it in thewp_enqueue_script
function? In that case the answer given by @Jack Johansson might be the better option. 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.– jaswrksNov 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.– jaswrksNov 8, 2017 at 4:54
-
The
$src
variable in thewp_enqueue_script
function is optional so if you don't link to the script in thewp_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. Nov 8, 2017 at 6:01