Tip Tuesday: WordPress URLs in JavaScript

| 0 comments

There are instances where you may need to use WordPress URLs in JavaScript files. However, hard-coding URLs is not an ideal solution, especially in situations where you have development and production environments. We can solve this by using the wp_localize_script() function.

A couple examples of using WordPress URLs in JavaScript include using your theme’s URL for a specific file within it, or using the core WordPress Ajax file. We will take a look at both of these examples. We’ll start off with our theme URL.

Enqueue Your Script

Before using wp_localize_script(), we must enqueue our script, with the wp_enqueue_script() function:

<?php wp_enqueue_script( 'my-scripts', get_template_directory_uri() . '/js/my-scripts.js', 'jquery', 1.0, true ); ?>

The first parameter is the name we give our script. The second is the location of our script. This script is in my theme, so I use the get_template_directory_uri() function, followed by the rest of the path to my script within my theme. The third parameter is the dependency, where I have used jquery as an example (this is the name of the script that this script is dependent on, if there is one). The fourth parameter is the version number of the script, and the fifth is if the script should go in the footer, which I have set to true.

Localize Your Script

Now we can use wp_localize_script(). Below our enqueue, we add the following:

<?php wp_localize_script( 'my-scripts', 'myScript', array( 'template_url' => get_bloginfo('template_url') ) ); ?>

The first parameter is the name of the JavaScript file where we will use the theme URL. The second parameter is the name of the JavaScript object we will use in our script file. It should not contain any dashes – use underscores, or camelCase. In the third parameter we are passing an array containing the theme’s directory using get_bloginfo().

To use this in our JavaScript file, my-scripts.js, we use the following:

var url = myScript.template_url+'/path/to/file';

myScript.template_url gives us the path to the theme’s directory, and then we concatenate the rest of the path to the file at the end. This gives us the full URL to the file without hard-coding. For example, this URL could be to a specific image file within your theme.

If you wanted to use the URL to a core WordPress file, for use in Ajax for example, we only need to make a couple simple changes:

<?php wp_localize_script( 'my-scripts', 'wpAjax', array( 'wpurl' => get_bloginfo('wpurl') ) ); ?>

Then in our JavaScript file we use:

var url = wpAjax.wpurl+'/wp-admin/admin-ajax.php';

wpAjax.wpurl gives us the path to the WordPress directory, and then we concatenate the rest of the path to the core Ajax file.