Using wp_enqueue_script and wp_enqueue_style with your WordPress Theme header

For the longest time I was including my Javascript files in WordPress with a simple Javascript statement in the header.php file. I’d reference the theme directory like this to make it portable.

<script type="text/javascript" src="<?php bloginfo('stylesheet_directory'); ?>/js/jquery.js"></script>
<script type="text/javascript" src="<?php bloginfo('stylesheet_directory'); ?>/js/1080d.js"></script>

Unfortunately this method isn’t compatible with some plugins. If you have a plugin that wants to use jQuery it has no way of knowing you have already included it on the page.

The proper way to add your Javascript is to use the wp_enqueue_script function. This is how I add it now.

wp_enqueue_script('jquery');
wp_enqueue_script('1080djs', get_bloginfo('stylesheet_directory') . '/js/1080d.js', array('jquery'), '20091014' );

If you want to be really fancy and put your Javascript at the bottom of the page in order to make YSlow happy, you can set it up like this:

wp_enqueue_script('jquery', '', '', '', '', TRUE);
wp_enqueue_script('1080djs', get_bloginfo('stylesheet_directory') . '/js/1080d.js', array('jquery'), '20091014', TRUE);

Then your Javascript files will be included when the wp_footer(); function is called. Otherwise they are included when wp_head(); is called.

CSS files can also be managed the same way with the wp_enqueue_style function. Using both of these methods will help you make sure your themes more portable and compatible with plugins.

This entry was posted in Code, General and tagged , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>