DEV Community

Hisman
Hisman

Posted on • Updated on

How to pass PHP variables to JavaScript in WordPress

When you're building a WordPress theme or plugin, sometimes you have JavaScript code that needs to use data/values from PHP. For instance, you need these values in your JavaScript code :

  • Homepage URL
  • Theme option values
  • WordPress posts data
  • etc

The easiest way to do that is by initializing those values into JavaScript objects in your header.php theme file or wp_head hook. For example :

<script>
var myThemeParams = {
   homeURL: <?php echo home_url(); ?>,
   themeOptions: <?php echo get_theme_mod( 'mytheme_options', false ); ?>,
}
</script>
Enter fullscreen mode Exit fullscreen mode

Even though it works but WordPress has been provided us with a function for doing something like that. It's called wp_add_inline_script.

wp_add_inline_script( $handle, $data, $position = 'after' )
Enter fullscreen mode Exit fullscreen mode
  • $handle : Name of the script to add the inline script to.
  • $data : String containing the JavaScript to be added.
  • $position : Whether to add the inline script before the handle or after.

That function will add an inline script before or after your JavaScript code. It actually can do more besides passing PHP variables to JavaScript. You can see another use case here.

So, to use wp_add_inline_script for passing variables from PHP to JavaScript, you need to set the position properties to before so that it'll add the inline script before your JS file. And then initialize a JavaScript object and set the value with data from PHP.

$myThemeParams = array(
    'homeURL' => home_url(),
    'themeOptions' => get_theme_mod( 'mytheme_options', false )
);
wp_enqueue_script( 'my-theme-script', get_template_directory_uri() . '/js/script.js' );
wp_add_inline_script( 'my-theme-script', 'var myThemeParams = ' . wp_json_encode( $myThemeParams ), 'before' );
Enter fullscreen mode Exit fullscreen mode

In your JavaScript you can access it like this:

console.log( myThemeParams.homeURL );
console.log( myThemeParams.themeOptions );
Enter fullscreen mode Exit fullscreen mode

Discussion (0)