Advertisement
Cheat Sheets

The Complete Guide to Proper JavaScript Usage With WordPress

by

I remember thinking "What the heck do we need JavaScript for, when we have Flash?" when I was fourteen. Although I still remember how I enjoyed coding stuff with ActionScript 2.0 back then, I saw how much one can achieve with JavaScript and fell in love with it. I'm not an expert on JavaScript (yet) but I can say I'm over and done with Flash for a long time.

When it comes to WordPress, the biggest blogging platform and content management system worldwide, JavaScript is - of course - very useful for many things: content sliders, lightbox galleries, slick shopping carts, UI elements like tabs or accordions... you name it. But how exactly should we use JavaScript with WordPress?

Returning or echoing a bunch of HTML script elements is one way to do it - and it's wrong. In this tutorial, we're going to see how to enqueue JavaScript files inside our pages and how to pass translatable data to the JavaScript code.


The Two Problems While Using JavaScript in WordPress Projects

There are basically two important problems you may encounter if you inject JavaScript files directly into WordPress with HTML code:

  • Duplicate code on the same page: Let's say you created a WordPress plugin and you need to include jQuery. You echo the proper script tag in the <head> and it works! But what if another plugin wants to use jQuery as well - how would it know that jQuery is already loaded in the <head>? It wouldn't, and even if the other plugin includes jQuery the right way, the page would still have two instances of jQuery, because you're not.
  • Problems with translation: Let's say that you're creating a lightbox gallery plugin and you need to pass strings like "Next", "Previous" and "Image X of Y". How do you do it without echoing inline JavaScript in the <head>?

The Right Way to Use JavaScript With WordPress

The solution to the first problem is simply "registering" and "enqueueing" the JS files with the two core functions of WordPress: wp_register_script() and wp_enqueue_script(). The second problem's solution is even easier: The core wp_localize_script() function allows you to pass translatable data into your JS code.

Registering JavaScript Files

Before you can "enqueue" the JavaScript files, you should "register" them first. And that's done simply using a function called wp_register_script():

<?php wp_register_script( $name, $url, $dependencies, $version, $load_in_footer ); ?>

Some notes on the parameters:

  • Name (required, string): The name of the script. You can choose any name you want, providing that's not used by another script.
  • URL (required, string): The URL of the script. No need to explain this, right? :)
  • Dependencies (optional, array): The name(s) of other scripts that our script depends on. For example, if your script depends on jQuery, it will need to be loaded after jQuery. In this case, you should use array( 'jquery' ) for this parameter.
  • Version (optional, string): The version number for your script. You can choose between providing a string, setting the parameter to null or leaving it empty. If you set it to string, that's going to be added to the output code like my-script.js?ver=1.2. If you leave the parameter empty, the version of your WordPress installation will be added as the version number. If you set it to null, nothing will be added.
  • Load in Footer (optional, boolean): When you enqueue this registered script, it will be loaded in the <head> section. But if you set this parameter to true, it will be loaded right before the closing <body> tag.

You can also "deregister" scripts that are already registered by the core or other plugins with the wp_deregister_script() function. It only accepts a 'name' parameter, which you provide the name of the script to be "deregistered". Obviously.

There are a bunch of scripts on the WordPress Codex that are already registered in the core. Although, you should double-check the list for the current version of WordPress, since it refers to WordPress version 3.3 and might be out of date.

Enqueueing JavaScript Files

You can register a script but that doesn't mean that it's going to be loaded automatically. After registering your scripts, you should "enqueue" them with the wp_enqueue_script() function:

<?php wp_enqueue_script( $name, $url, $dependencies, $version, $load_in_footer ); ?>

Some notes on the parameters:

  • Name (required, string): The name of the script.
  • URL (optional, string): The URL of the script. As you can see, this time the URL parameter is optional because if you already registered the script, you can just provide the name and you're good to go. But if you didn't register your script, you must provide a URL for this parameter.
  • Dependencies (optional, array): The name(s) of other scripts that our script depends on.
  • Version (optional, string): The version number for your script.
  • Load in footer (optional, boolean): If set to true, the script will be loaded right before <body> closes.

You can also "dequeue" scripts with the wp_dequeue_script() function. Similar to the wp_deregister_script() function, it only accepts a 'name' parameter.

You can check the "state" of a script with the wp_script_is() function. For example, if you want to check if 'my-script' is enqueued, simply use wp_script_is( 'my-script', 'queue' ) in an if statement.

Hooks to Enqueue Your Scripts

The right way to enqueue your scripts (and styles, too) is using the hooks below:

  • wp_enqueue_scripts - This one enqueues scripts in the front end of your website.
  • admin_enqueue_scripts - This one enqueues scripts in the back end of your website.
  • login_enqueue_scripts - This one enqueues scripts in your login screen.
<?php
function my_scripts_loader() {
	wp_enqueue_script( 'my-js', 'filename.js', false );
}
add_action( 'wp_enqueue_scripts', 'my_scripts_loader' );
?>

Due to compatibility issues, you mustn't use the hooks named admin_print_scripts or admin_print_styles.

For further reading on including JavaScript (and CSS!) in your themes and plugins, you can refer to How to Include JavaScript and CSS in Your WordPress Themes and Plugins by Japh Thomson on Wptuts+.

Passing Translatable Data Inside JavaScript

When it comes to localization, JavaScript is always a problem with WordPress... because so many people doesn't know the neat little function called wp_localize_script():

<?php
$l10n_data = array(
	'nextItem' => __( 'Next', 'my-script' ),
	'prevItem' => __( 'Previous', 'my-script' ),
	'imageTitle' => __( 'Image %d of %d', 'my-script' )
);

wp_localize_script(
	'name-of-the-script', // (required) the name of the script, 'my-script' for example
	'nameOfTheObject', // (required) the name of the script, 'my-script' for example
	$l10n_data // (required) the data to be passed, which can be translatable with the __() function
);
?>

After registering, enqueueing and localizing the script, you can pass the localized variable in your script by using the name of the object and names of the data, like alert( nameOfTheObject.prevItem );!

You can refer to Pipping Williamson's article for a more thorough analysis.


Wrapping Up

There is a reason why WordPress is the biggest content management system in the world: Its power comes from its flexibility. And I believe this tutorial proves (once again) how flexible it is.

This tutorial covers pretty much what WordPress offers about JavaScript usage for our projects. Do you have any more tips or techniques on JavaScript and WordPress? Tell us about it!

Related Posts
  • Code
    Theme Development
    How to Pass PHP Data and Strings to JavaScript in WordPressPhp js 400
    It's good practice to put all your data in static strings in your PHP files. If you need to use some data in JavaScript later on, it's also good practice to put your data as data-* attributes in your HTML. But in some certain scenarios, you have no choice but to pass strings directly to your JavaScript code. If you are including a JavaScript library, and you've found yourself initializing a JavaScript object inside your header.php then assigning data to its properties, then this article is for you. This article will teach you on how to properly pass PHP data and static strings to your JavaScript library.Read More…
  • Code
    Creative Coding
    Using the Included Password Strength Meter Script in WordPressPassword meter 400
    WordPress uses a pretty nifty password strength script that is used to display whether the passwords you entered in the WordPress admin are: not the same, very weak, weak, medium or strong. Currently this script is only used when creating creating new users and when changing your password in your admin. In this article, I will be teaching you on how to use the WordPress' password strength meter in your own forms.Read More…
  • Code
    Plugins
    Using HighCharts in WP-AdminHighcharts 400
    Charts are a great way to present data. They make data more digestible by making it visually appealing. In WordPress, there is no built-in method for getting posts and pages data in a graphical form. Although, there are certain plugins available which integrate Google Analytics with WordPress, but they are overkill if you want to get only a portion of that data. Also, nothing should keep you from learning new techniques and to dive straight into the subject is the best way to learn.Read More…
  • Code
    Plugins
    Enhancing the Search Form With typeahead.jsTypeahead ltgrey 400
    The WordPress search form doesn't offer any bells and whistles by default. If it's already included in your theme, or you've added the search widget to one of your sidebars, you can attest to that. One way to greatly improve its functionality is to include an autocomplete script to help enhance the efficiency of how relevant search queries are relayed.Read More…
  • Code
    Plugins
    How to Create a WordPress Avatar Management Plugin from Scratch: Getting StartedPreview
    Avatar Manager for WordPress is a sweet and simple plugin for storing avatars locally and more. Easily. Enhance your WordPress website by letting your users choose between using Gravatar or a self-hosted avatar image right from their profile screen. Improved workflow, on-demand image generation and custom user permissions under a native interface. Say hello to the Avatar Manager plugin.Read More…
  • Code
    Tips
    Common WordPress Development Mistakes and How to Fix ThemCommon wordpress development mistakes and how to fix them
    With WordPress becoming more and more popular there is a massive amount of code being generated by users, agencies and marketplaces. I've been working with WordPress for a long time and it amazes me how many developers out there are making the same mistakes over and over again. I'm going to go through some of the most common development mistakes and how you can easily fix them, and going forward make your code better!Read More…