Include jQuery or JavaScripts in WordPress

Plugin and theme authors use jQuery for their special effects, but there seems to be some confusion about the proper way to include JavaScript files in WordPress. If you’d like to use jQuery effects on your pages or in your theme, or if you want to include any javascript plugin or personal script, read on to see how to do it properly with WordPress sites.

Queue Up Your Scripts with Actions

Since jQuery itself is already included in the core of WordPress, how should we include a javascript file that we’ve created or even one of the popular jQuery plugins that rely on jQuery? WordPress helps us in this endeavor with a function called ‘wp_enqueue_script()‘ and two actions that are used to call this special function.

The actions are used for either the user side or the admin side, depending on the purpose of your javascript. Use the ‘wp_enqueue_scripts‘ action to call wp_enqueue_script() for use in your themes. If the script functionality is needed on the admin side, use ‘admin_enqueue_scripts‘ action instead.

The format of the wp_enqueue_script() function call is as follows:

[plain]
wp_enqueue_script(‘$handle’, ‘$src’, ‘$deps’, ‘$ver’, ‘$in_footer’);
[/plain]

where $handle is the name of the script as a lowercase string, $src is the URL to the script, $deps is an array of scripts that the script you’re calling depends on or the scripts that must be loaded first for your script to work, $ver is the script’s version number in string format, and $in_footer is a boolean value to indicate whether the script should be loaded in the <head> or at the end of the <body> in the footer.

The $handle string is the only required parameter, so the other four parameters are optional. The $src, $ver, and $in_footer parameters default values are ‘false’, and $deps defaults to an empty array.

It seems that $src would need to be a required option, but WordPress already knows about several scripts and where to find them. Consult the list of default scripts included with WordPress to pick up their handles.

For example, to queue the jQuery Color plugin, we’d simply use this:

[plain]
wp_enqueue_script(‘jquery-color’);
[/plain]

To include a script and specify the source, try this for including the jQuery Cycle plugin in the <head>:

[plain]
wp_enqueue_script(‘jquery-cycle’, ‘URL’, array(‘jquery’), ‘1.3.2’);
[/plain]

The URL should not be a hard-coded value for local scripts. Refer to the Function Reference pages in the codex for proper URL formats for plugins and themes.

Register Your Scripts First

Make sure that your scripts are registered first before calling them. Registering a script basically tells WordPress where to find the code for your script. Use the function wp_register_script() to specify the location and handle of your script. The format is similar to the wp_enqueue_script() function:

[plain]
wp_register_script(‘$handle’, ‘$src’, ‘$deps’, ‘$ver’, ‘$in_footer’);
[/plain]

The parameters have the same meanings and default values as used with wp_enqueue_script(). When in doubt, see what the WordPress Codex has to say about wp_enqueue_script() and wp_register_script().

Create a Function for the Header

Put it all together using wp_register_script(), wp_enqueue_script(), and the appropriate action to call the functions. Create a simple function, like id_scripts() below, and use the add_action() hook to queue up the scripts.

[crayon]
function id_scripts() {
wp_register_script(‘script_alpha’, ‘URL’, array(‘jquery’), ‘1.0’);
wp_enqueue_script(‘script_alpha’);
}
add_action(‘wp_enqueue_scripts’, ‘id_scripts’);
[/crayon]

As a side note jQuery itself doesn’t have to be queued via a statement like wp_enqueue_script('jquery');, because it is listed as a dependency of ‘script-alpha‘ in this case.

When enqueuing a custom script that depends on a jQuery plugin, specify jQuery and its plugin in the $deps parameter of the wp_register_script() action for the custom script. For example, if your custom script depends on the jQuery Cycle plugin, which itself depends on jQuery, use array('jquery', 'jquery-cycle') for the $deps parameter. This specifies that both jQuery and its plugin Cycle should be loaded (in that order) before the custom script.

Place this code in the header.php of your theme. Remember, first register the javascript file, then enqueue it and make sure this is done before the wp_head(); statement. Your custom script can then be placed in header.php after the wp_head() call.

Use Theme functions.php to Safely Reference Your Script

When using a child theme take note that the header.php in a child theme will override the default header.php in the parent theme. Instead of placing the script-queuing code in the header, one could more safely put this code in functions.php. The advantage to that way is that the functions.php of a child theme is processed before the functions.php of the parent theme. Both the parent and child theme functions.php are processed, unlike header.php files.

If you’re the least bit unsure about messing with header.php, then just use functions.php to queue up your javascript files. Don’t forget the opening and closing PHP tags in functions.php, else it won’t work. Put the javascript that would come after the wp_head() call in a separate .js file in the child theme and you’re good to go.

Verify that everything is working correctly by viewing the source of the HTML document for a WordPress post that should have the script included. The <script> tags should be visible in the header or in the footer depending on how the scripts were called.

Enable Caching in Firefox for Faster Web Sites

Using an .htaccess file to specify that images should be cached is one way to speed up the time it takes for your web pages to appear. Those of us still using older browsers will thank you for using an Expires Header in .htaccess to manage caching.

Yet another good reason to upgrade your browser is to take advantage of newer features. Caching of images and other often-used files can be controlled by your browser.

IE 9 apparently has caching defaulted to ON. Firefox 5 does not.

Here’s how to enable caching in Firefox.

  • Type “about:config” in the address bar and hit enter.
  • Accept the warning by clicking on the “I’ll be careful, I promise!” button.
  • Scroll down to ‘browser.cache.disk.enable’ and double click. You will see the value in the fourth column toggle from false to true, if caching was not enabled already.
  • Scroll down to ‘browser.cache.memory.enable’ and double click to enable by setting it to true.

That’s it! The performance of your Firefox browser will speed up, noticeably so. After enabling caching, the time to download pages from a client’s site went from 6-10 seconds to 2-3 seconds!

How To Download A Header Image Just Once

While checking links on a client’s re-vamped web site, I noticed that the header image would be re-loaded for each page visited on the site. I’d forgotten to set the .htaccess file with an Expires Header to ensure that the images would be downloaded just one time by a site visitor.

Making the content appear quickly in front of site visitors should be a goal for all site developers. And besides, reducing the load on your server is always a good idea, don’t you think?

To cache a header image, or other images for that matter, or to make sure that files aren’t downloaded too often, use an Expires Header in your .htaccess file.

#Expire Header
<FilesMatch "\.(ico|jpg|jpeg|png|gif|js|css|swf)$">
ExpiresDefault "access plus 2 months"
</FilesMatch>

Note that all types of image files, as well as stylesheets, javascript, flash and other file types, can be cached with this Expire Header.

Paths For Building WordPress Themes or Plugins

When tinkering with the code that runs WordPress it’s very important to get the correct path to a file. Of course it is or else the files can’t be found and your new functionality won’t work.

According to the Codex –

In Version 2.6, users were given the ability to move their /wp-content/ directory to anywhere they want, and many users already keep all WordPress files (like /wp-admin/ and /wp-includes/) in an unusual place.

In case you’ve moved the files for your WP installation, you probably have a good handle on paths and how to traverse them. For those who don’t, it can be a hair-pulling experience to find the right path. Once the right path is found, work can continue.

WordPress Paths

To help avoid those DUH! moments, here are some functions and constants that WordPress has defined regarding paths. Once you’re familiar with these functions, writing useful and working code should become easier. Optional parameters may be of use in modifying the output for several of the following templates, including $path, $file or $scheme.

plugin_basename()
Usage: plugin_basename(__FILE__); Returns: the name of the plugin and file, such as “myPlugin/myPlugin.php”
get_theme_root()
Usage: get_theme_root(); Returns: path to themes directory. No trailing slash.
get_theme_root_uri()
Usage: get_theme_root_uri(); Returns: URI for themes directory. No trailing slash.
get_theme_roots()
Usage: get_theme_roots(); Returns: Themes directory with a leading slash, like “/themes”.
site_url()
Usage: site_url(); Returns: Site directory with no trailing slash.
http://www.site.com OR http://www.site.com/wordpress
admin_url()
Usage: admin_url(); Returns: Admin directory with trailing slash.
http://www.site.com/wp-admin/
content_url()
Usage: content_url(); Returns: Content directory with trailing slash.
http://www.site.com/wp-content/
plugins_url()
Usage: plugins_url(); Returns: Plugins directory with trailing slash.
http://www.site.com/wp-content/plugins/
includes_url()
Usage: includes_url(); Returns: Includes directory with trailing slash.
http://www.site.com/wp-includes/
home_url()
Usage: home_url(); Returns: Home directory with no trailing slash.
http://www.site.com
ABSPATH (constant)
Usage: ABSPATH. Returns: Home directory with no trailing slash.
TEMPLATEPATH (constant)
Usage: TEMPLATEPATH. Returns: Path to current theme with no trailing slash.

There are a few more functions for multisite installations and backwards capability specified in the Codex.

PHP Paths

Some PHP functions worth noting –

  • __FILE__ returns the filename of the script that is currently being run
  • dirname() returns parent directory’s path for a given filename with no trailing slash
  • basename() returns the filename component of path without any parent directories
  • getcwd() returns current working directory

Use the functions or constants indicated to build your paths instead of hard-coding them. You’ll save yourself a LOT of trouble when it comes time to move your WordPress installation to a new server or directory.