Javascript and WordPress – The Definitive Guide

Using custom JavaScript code in a WordPress theme or plugin is, in many cases, a given. Fortunately, WordPress comes bundled with a selection of popular Javascript libraries (jQuery, Prototype and others) for use with your plugins and themes. Many users, however, simply write the `<script>` tags in the header.php file of their theme or as part of a function in their plugin that is run in the header of the theme being used. This is a potential problem area that can have you, the developer, sitting for ages looking at your code and wondering why plugin `X` isn’t working correctly when theme `Y` is active. This guide aims to provide an understanding of how to correctly enqueue Javascript in WordPress and how to avoid potential Javascript conflicts.

Okay, what are we doing here?

We’re going to enqueue the Javascript files, used by our WordPress plugin or theme, using the correct method and the wp_enqueue_script()function. We will be adding an action to the wp_print_scripts() action and, inside a function within our theme or plugin, running the wp_enqueue_script() function. We will also be including the Javascript in the administration area only, creating dependencies between our various custom Javascript files and enqueuing the scripts on only a specific page in the administration area.

Why you need to be on the WordPress Support forums

Do you remember a time when those one or two lines of code just didn’t make sense? When your theme looked different across various internet browsers and you had no idea why? Do you remember when last that happened to you? Those were the times when you more than likely visited a support forum, posting with the final few morsels of energy you had left. Did you find an answer?

Support forums, in general, seem to be notorious for hosting lots of posts about problems, with few posts offering solutions to those problems. I see this on a regular basis on many web development support forums… many queries and few answers.