Select Page
Adding JavaScript variables via PHP
This is quite useful when you have several JavaScript functions which requires to define url (e.g. ajax calls). Rather than hardcoding link inside each function we can specify one variable. In this way, it can be used in different functions.

This is quite useful when you have several JavaScript functions which requires to define url (e.g. ajax calls). Rather than hardcoding link inside each function we can specify one variable. In this way, it can be used in different functions.

Creating the function

function set_js_vars() {
    wp_register_script( 'jsVars', '');
    wp_localize_script( 'jsVars', 'page_urls', array(
        'ajaxUrl' => admin_url( 'admin-ajax.php' ),
        'homeURL' => get_home_url(),
        'templateDir' => get_template_directory_uri(),
    ) );
    wp_enqueue_script( 'jsVars' );
}

add_action( 'wp_enqueue_scripts', 'set_js_vars' );

Now lets break it down ,

Line 2: We need to use wp_register_script to register a blank script to do this we set the second paremiter to an empty string (‘ ‘).

Line 3-7: We assign all the variables we want as an array to the registered script using the wp_localize_script funtion.

Line 8: We actually enqueue the script (blank + variables).

Line 11: We use the correct hook to run this function in the WordPress life cycle

Preloader