Using PHP variables inside Javascript with WordPress.

We’ve all been there, we’ve needed to pass a variable into our script when working with WordPress. For things like passing the Template Directory URI across.

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

We’ve all been there, we’ve needed to pass a PHP variable into our script when working with WordPress. For things like passing the Template Directory URI across.

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.

Usage

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.


<?php
// 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()
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
    array(
        '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.

UncoverWP

Want us to email you occasionally with our latest courses, news & updates?

We use cookies to ensure that we give you the best possible experience on our website. If you continue to use this site we will assume that you are happy with it. OK Privacy Policy