< script > tags into the head section of the pages (or at the bottom of the body section, in some cases). The most obvious way to achieve this in a WordPress theme is using the wp_head hook. You can create a function that echoes the
< script > tags and runs when the
wp_head hook is triggered. This method is quite often used by theme and plugin developers.
However, if you simply inject scripts into the header, WordPress has no idea the code is there, and so it can’t handle conflicts and dependencies properly. WordPress ships with a number of JS libraries, including JQuery, and they’re loaded only when required as a dependency to a properly registered script. Because WordPress sites are usually loaded with plugins and a theme, each of which is likely to want to include code on the page, the CMS provides a mechanism for properly managing script loading.
The proper technique is to use the
wp_enque_scripts functions (or one of its variants for loading scripts in different parts of the interface).
For full details on how to do this manually, take a look at the comprehensive documentation in the WordPress Codex. In this article I’m going to take a shortcut and discuss a service that will generate the code for you.
GenerateWP is a nifty web service that is capable of generating many different code snippets for inclusion in WordPress themes and plugins. GenerateWP covers a lot of ground, including post type, sidebar, shortcode, shortcode, and taxonomy code generation, but here we’ll stick with script inclusion.
If you take a look at the page for registering WordPress scripts, and click on the Script 1 tab, you’ll see a set of text boxes in which to enter the relevant information, beneath which is a code snippet that can be pasted into your theme (usually in the functions.php file).
The page is fairly self-explanatory, but there are a couple of potential gotchas.
The Handle/Name should contain the name of the script, which in reality can be any name you like, but it makes sense to give it a relevant name.
Script Dependencies is a list of the scripts on which the file depends, such as JQuery, which WordPress will load automatically.
Script location is the location in the HTML page that would you would like to have the script loaded; it’s not the location of the script on the filesystem or remote server, which is indicated by Script URL.
Script version is an arbitrary number for keeping track of things.
Generally, you’ll want to change Enqueue Script to ‘yes’.
So, lets say you wanted to include the JQuery progress bar PACE in your theme. The GenerateWP settings would look like this:
And the resulting code looks like this.