Proper JavaScript Usage With 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

Duplicate code on the same page
If you echo the proper script tag in the 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? 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?

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 ); ?>

Parameters
Name (required, string): The name of the script.

URL (required, string): The URL of the script.

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 section. But if you set this parameter to true, it will be loaded right before the closing tag.

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 ); ?>

Parameters
Name (required, string): The name of the script.

URL (required, string): The URL of the script.

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 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.

Hooks to Enqueue Your Scripts

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.

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 );!

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.

Leave a Reply

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