Using PHP variables inside Javascript with WordPress.

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.

How do we do it?

Well, I’ll tell you. 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 register our script properly using wp_enqueue_script(), we can then let wp_localize_script() work it’s magic.

// wp_enqueue_script
wp_enqueue_script( 'ikreativ_theme_script', get_template_directory_uri() . '/assets/js/script.js', array( 'jquery' ), '1.0.0', true );

// pass our vars to the script using wp_localize_script
wp_localize_script(
    'ikreativ_theme_script',
    'ikreativ_script_vars',
    // register an array of vars
    array(
        'template_directory' => get_template_directory_uri()
    )
);

So, now we’ve registered our script and passed our vars to it, we can access them inside our script like so:

// pass our php var into our script
ikreativ_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.

iKreativ
Up Next:
iKreativ