To refine a previous post on WordPress and jQuery and the use of the wp_enqueue_script function, its paths and dependencies.
As a barebones example, this is how we do it when we we’re enqueueing – if that’s a word – the jQuery Cycle plugin, so that we can make a slideshow on the page.
The important point is probably in the dependencies – firstly, the Cycle plugin depends on jQuery, so has to be loaded after – secondly, our custom script to run the whole process on depends on the jQuery Cycle plugin and therefore also on jQuery and is the last to load.
The custom script we’ve written is in them_directory/scripts/them.cycle.js – something very simple, like this:-
jQuery(document).ready(function($) {
$('#images').cycle({
//some parameters
});
});
(Don’t forget, the dollar $ object isn’t defined in WordPress jQuery (historical reasons) – hence the form of the first line)
This is client-display side javascript, as opposed to admin-side, (which tends to follow slightly different rules in the WordPress setup) and in this case, the action hook ‘template_redirect’ is usually the time to do it.
To enqueue the jQuery library itself is simple – it’s already registered by default in WordPress, no need to specify other than the default path and version.
So in functions.php
add_action('template_redirect', 'them_js_head_load');
function them_js_head_load(){
//register the plugin
wp_enqueue_script('jquery-cycle', THEM_TEMPLATEURL.'/scripts/jquery.cycle.lite.min.js', array('jquery'), '1.0');
//register the custom script
wp_enqueue_script('them-cycle', THEM_TEMPLATEURL.'/scripts/them.cycle.js', array('jquery', 'jquery-cycle'), '1.0');
}
Note for convenience and efficiency, we’ve previously defined
define(THEM_TEMPLATEURL, get_bloginfo('template_directory'));
And what you end up with in the page source should be something like this – javascripts loaded in the right place in the page head, up and running
<script type=’text/javascript’ src=’http://localhost/test/wp-content/themes/this-theme/scripts/jquery.cycle.lite.min.js?ver=1.0′></script>
<script type=’text/javascript’ src=’http://localhost/test/wp-content/themes/this-theme/scripts/them.cycle.js?ver=1.0′></script>
