HOWTO: Add script to your theme using wp_enqueue_script

TO add a javascript file to your theme its easy to use header.php in your theme folder. However if there are plugins using same script libraries (like jquery, scriptaculous ) it may cause errors. Here i will show you how to add javascripts to your theme in a safe way using wp_enqueue_script.

After many plugins started embedding javascript files in wordpress using wp_head hook, WP developers created wp_enqueue_script to safely include script files. This function ensures that the library file will be loaded only once in the theme. For example to include jquery in your themes you can easily use this call:

wp_enqueue_script('jquery');

JQuery is a common script library file that comes with wordpress so it is already defined with jquery tag. To add a custom script you need to specify more information. To include jquery cycle plugin you will need to use:

wp_enqueue_script('jquery'); // This will be needed by jQuery.Cycle
wp_enqueue_script('cycle', 'http://cloud.github.com/downloads/malsup/cycle/jquery.cycle.all.latest.js', array('jquery')); // Load jQuery.Cycle

As you can see, it is quite simpple. Let me explain this code:

'jquery'
You need to specify a tag for all your scripts to avoid multiple includes.
'http://cloud.github.com/downloads/malsup/cycle/jquery.cycle.all.latest.js'
This is the src for the script tag.
array('jquery')
In this part you can specify dependencies using their tags in an array.

Here is another example with a custom script in theme folder:

wp_enqueue_script( 'jquery' );
wp_enqueue_script( 'theme-script', get_template_directory_uri() . '/js/theme.js', 'jquery' );

We included theme.js in the theme directory using get_template_directory_uri(). Including script files this way will ensure path will be correct even if theme directory is renamed.

It is a good practice to enqueue scripts in an init function like this:

function my_theme_scripts() {
  wp_enqueue_script( 'jquery' );
  wp_enqueue_script( 'cycle', 'http://cloud.github.com/downloads/malsup/cycle/jquery.cycle.all.latest.js', array( 'jquery' ) );
  wp_enqueue_script( 'theme-script', get_template_directory_uri() . '/js/theme.js', 'jquery' );
}    
 
add_action('init', 'my_theme_scripts');

Just paste this code in your functions.php file and it will load the scripts in a safe and easy way.

I hope you found this tutorial useful.



NS Weight Release