Matteo Bandiera

Web Developer

Wordpress configuration

Using wp_localize_script() in WordPress

- by

I’ve recently used wp_localize_script function for building a custom contact form.

 

What is wp_localize_script?

If you don’t know what wp_localize_script is and how it works you can read about it on the WordPress codex website.

Localizes a registered script with data for a JavaScript variable.

 

How can it be useful for our code?

I’ve used it when using Ajax. In particular I needed to pass the URL of admin-ajax.php into my JavaScript, rather than hardcode it since it is defined only on the backend side of WordPress. So, without further ado, let’s see how to implement it.
First of all we need to source a script via wp_enqueue_script. For example in function.php we have:

function mb_scripts() {
 
  wp_register_script( 'mb-scripts', get_template_directory_uri() . '/js/scripts.js', array( 'jquery' ), '1.0.0', true );
  wp_enqueue_script( 'mb-scripts' );
 
}
add_action( 'wp_enqueue_scripts', 'mb_scripts' );

 
Now we are able to add a call to wp_localize_script and pass the data we need in our JavaScript file.
What we need is the live URL of admin-ajax.php and this is how we do it:

function mb_scripts() {
 
  wp_register_script( 'mb-scripts', get_template_directory_uri() . '/js/scripts.js', array( 'jquery' ), '1.0.0', true );
  /** ADD THIS LINE */
  wp_localize_script( 'mb-scripts', 'ajax_params', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
  /** ---- */
  wp_enqueue_script( 'mb-scripts' );
 
}
add_action( 'wp_enqueue_scripts', 'mb_scripts' );

 
From the official documentation we can see wp_localize_script takes three parameters. Let’s see what they are.

  • $handle: The registered script handle you are attaching the data for. mb-scripts in our case.
  • $name: The name of the variable which will contain the data and that we will be accessing from our JavaScript file.
  • $data: The data itself. It can be either a single- or multi- dimensional array.

 
Now that we have our function.php in place we can move on to the scripts.js.

jQuery(document).ready(function($) {
 
    var ajax_url = ajax_params.ajaxurl; // ajax_paramas is available as a JavaScript object
    var formData = {
        "name"      : $( "#name" ).val(),
        "message"   : $( "#message" ).val(),
        "action"    : $("#action").val(),  // Used from the backend to setup the action will be called on this AJAX request
    };
    $.ajax({
        type    : "POST",
        url     : ajax_params.ajaxurl,
        data    : formData,
        dataType: "json",  
    }).done(function(data){
        console.log(data);
    });
});

 

Important Note

wp_localize_script() MUST be called after the script has been registered using wp_register_script() or wp_enqueue_script().