How to pass PHP variables to JavaScript in WordPress

Internet 2021-09-29 20:25:54 3 2,686

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>

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' )
    $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' );

In your JavaScript you can access it like this:

console.log( myThemeParams.homeURL );
console.log( myThemeParams.themeOptions );

#WordPress#


Your opinion

Already have 3 Article answer
  • forex 1楼
    Hi would you mind letting me know which hosting company you're working with? I've loaded your blog in 3 completely different web browsers and I must say this blog loads a lot faster then most. Can you recommend a good web hosting provider at a fair price? Thank you, I appreciate it!
    发布于 2022/03/17 09:11
  • free freaky porno 2楼
    Hi, all is going fine here and ofcourse every one is sharing data, that's in fact good, keep up writing.
    发布于 2022/03/11 07:16
  • cara buat robot forex sederhana 3楼
    Hello, all is going well here and ofcourse every one is sharing facts, that's in fact good, keep up writing.
    发布于 2022/02/03 21:59