webappguides
Create Wordpress Theme From Scratch! Build Your Own

What is wp_localize_script and its Functions in WordPress

Among the WordPress functions for including javascript files in a page, wp_localize_script does that task

Then, if you ask yourself what is wp_localize_script, here is the answer

wp_localize_script is the WordPress function special for localizing a script with data to be used by a javascript codes

If a template intends to use localization API, it will be required to use this function

Since the API is provided by PHP and not a javascript directly t in a front end

What are the wp_localize_script parameters?

The function passes three parameters

Each parameter’s value must be specified as there is no optional variable

If you don’t define any among the three, you won’t be able to use localization API

These arguments include

  1. $handle
  2. $object_name
  3. $l10n

Handle enters first followed by object name and then data in the form of an array

$handle

In WordPress, a handle is a unique name given to a script that you localize

Hence, it can be any non-repeating name

The output of the $handle appears in a script tag

Here below is a handle name that was given for admin-ajax.php

wp_localize_scrip handle name

The unique identifier can be seen after the keyword id

$object_name

It is a unique object name that can retrieve a data value of a returned URL of the localized script

A javascript code uses $object_name to access the localization API data

For example, when a page uses WordPress ajax, the object name value will be https://localhost/wp-admin/ajax-admin.php

The object retrieves the given directory using a specified key

$l10n

It is an argument written in numeronym format, which means localization

The parameter passes the actual data needed to be adopted by a particular WordPress page

The $l10n  can be an associative array with an URL for retrieving certain registered WordPress API

For example, for the page that is going to execute WordPress ajax for a  load more button,

The array element will look like this

array('ajaxurl'=>admin_url('admin-ajax.php')

The element returns the path directory in which the ajax PHP file resides

Function of the wp_localize_script

The function wp_localize_script takes data from the server-side to the client through javascript

This gives the ability to other js files to use the data for attaining other goals on a page

When you implement it properly you will see its output in a <script> tag as you can see in the example section

Another task of the localization function is to access a pre-defined scripts

WordPress Framework always registers some javascript that has been defined within a system before

Such scripts can add a certain functionality required by a website

To access them, a theme should use the wp_localize_script function

A good example is a WordPress ajax

In short, wp_localize_script is a bridge that sends data from PHP to JavaScript in WordPress

wp_localize_script Examples

Here is an example of how to use the localization application programming interface in WordPress

The API relies on wp_localization_script.

The function can be part of other functions in the functions.php file

add_action('wp_enqueue_scripts', 'add_ajax_pagination_file');
function add_ajax_pagination_file(){
   wp_enqueue_script('paginationByAjax',get_template_directory_uri().'/'.'js/pagination_ajax_wp.js',array( 'jquery' ),1.0);
   wp_localize_script( 'paginationByAjax', 'ajaxpagination', array(
    'ajaxurl' => admin_url( 'admin-ajax.php’ )
));
}

The output can be found in the HTML source of a page.

And this is how it looks like
<script type='text/javascript' id='paginationByAjax-js-extra'>
/* <![CDATA[ */
var ajaxpagination = {"ajaxurl":"http:\/\/localhost\/webappscoach\/wp-admin\/admin-ajax.php"};
/* ]]> */
</script>

-wp_localize_script-output

As you can see, the first parameter value of wp_localize_scripts has turned to be the id attribute of the entire script

To get the required output, the function needs a hook to be executed

The hook that can add a function to the desired page is add_action

According to WordPress, add_action is the action that hooks important core launches during a system execution

Some jquery or pure javascript is now able to use the object “ajaxpagination” to access the given data value

Using wp_localize_script in a custom page

Once you implement the function successfully, all pages of the website will be affected

Hence the function can provide data to a specific custom page or taxonomy

There is no magic or extra manipulation for localizing a particular script

What matters is the registration of the script

wp_localize_script cannot work without adding the script before

The new script is going to be part of the template by registering it using wp_register_script

How to register script

Add the code that contains wp_register_script in a functions.php

This is how to do it

function register_custom_script() {

wp_register_script("myCustomScript",get_template_directory_uri()."/js/mycustom.js");

}

add_action ('wp_enqueue_script', 'register_custom_script');

When a certain page wants to include mycustom.js, it should call wp_localize_script

The handle argument of wp_localize_script is the first parameter of the wp_register_script which is myCustomScript

How does it differ from wp_enqueue_script?

wp_enqueue_script doesn’t need a script to be registered beforehand

wp_enqueue_script can add any javascript or stylesheet file as long as it does exist in a theme directory or on another host

This function includes five arguments

But the function requires the first two parameters to be specified

While the rest are optional

Although the WordPress localization function passes three arguments

And they cannot be empty

In fact, wp_enqueue_script does register a script too

It works mainly on a client-side

To understand how wp_enqueue_script enqueues CSS and javascript just check this page loading CSS and js in WordPress

How to add ajax with wp_localize_script

There are a few steps to consider for adding WordPress ajax using wp_localize_script

First, add the new function in a functions.php file

Inside the function, put wp_enqueue_script to register the URL of the customized script

This snippet provides the summary of adding WordPress ajax

add_action('wp_enqueue_scripts', 'add_ajax_pagination_file');
function add_ajax_pagination_file(){
   wp_enqueue_script('paginationByAjax',get_template_directory_uri().'/'.'js/pagination_ajax_wp.js',array( 'jquery' ),1.0);
   wp_localize_script( 'paginationByAjax', 'ajaxpagination', array(
    'ajaxurl' => admin_url( 'admin-ajax.php‘ )
));
}

Final Thoughts

wp_localization_script is a useful method to deploy the WordPress built-in script

Currently, WordPress offers most of the API in a PHP

Some of these APIs provide features that improve the UI/UX of the page

But for customized script wp_enqueue_script is enough to load the js to a page