Using PHP variables inside Javascript with WordPress

How do we do it?

WordPress has a handy little function called wp_localize_script() to properly handle just this. You can read the function reference here.


We first need to enqueue the which we would like to pass the PHP variable(s) to. We’re going to use wp_enqueue_script(), for this, then we can then let wp_localize_script() work it’s magic.

// enqueue the script we would like to pass our PHP variables to
wp_enqueue_script( 'uncoverwp', get_template_directory_uri() . '/assets/js/script.js', array( 'jquery' ), '1.0.0', true );

// pass our PHP variables to the script we enqueued above using wp_localize_script()
    'uncoverwp', // the handle of the script we enqueued above
    'uncoverwp_script_vars', // object name to access our PHP variables from in our script
    // register an array of variables we would like to use in our script
        'template_directory' => get_template_directory_uri() // template_directory now contains the path to our template directory

So, now we’ve enqueued our script and passed our PHP variables to it, we can access them inside our script like so:

// use our assigned PHP variable in our script
uncoverwp_script_vars.template_directory + '/path/to/some/file.php'


Pretty cool huh? You can also pass strings into your script that can then be translated if you’re translating a theme for instance. Neat.


About Me

Designer. Developer. Hacker. Senior Reviewer / Content Specialist @envato