How to include variables from PHP to a JS file in WordPress

How to include variables from PHP to a JS file in WordPress

One way is to use the wp_add_inline_script() function to add inline scripts to your enqueued JavaScript file. This function allows you to add PHP code directly to your JavaScript file, and you can use this to pass PHP variables to your JavaScript code.

Home / Blog / Unspecified / How to include variables from PHP to a JS file in WordPress

One way is to use the wp_add_inline_script() function to add inline scripts to your enqueued JavaScript file. This function allows you to add PHP code directly to your JavaScript file, and you can use this to pass PHP variables to your JavaScript code.

Here’s an example of how you can use wp_add_inline_script() to pass a PHP variable to a JavaScript file:

function mytheme_enqueue_scripts() {
    wp_enqueue_script( 'mytheme-script', get_template_directory_uri() . '/js/my-script.js', array( 'jquery' ), '1.0.0', true );

    // Add inline script to pass PHP variable to JS file
    $my_var = 'Hello, world!';
    $inline_script = 'var my_var = "' . $my_var . '";';
    wp_add_inline_script( 'mytheme-script', $inline_script );
}
add_action( 'wp_enqueue_scripts', 'mytheme_enqueue_scripts' );

In the example above, we’re using wp_add_inline_script() to add a script that sets a JavaScript variable my_var to the value of the PHP variable $my_var. We can then access this variable in our my-script.js file like so:

console.log(my_var); // outputs 'Hello, world!'

Another way to pass variables from PHP to JavaScript is to use the wp_localize_script() function to localize a script. This function allows you to pass a PHP array to your JavaScript code, and the array is then made available in your JavaScript code as a JavaScript object.

Here’s an example of how you can use wp_localize_script() to pass a PHP array to a JavaScript file:

function mytheme_enqueue_scripts() {
    wp_enqueue_script( 'mytheme-script', get_template_directory_uri() . '/js/my-script.js', array( 'jquery' ), '1.0.0', true );

    // Localize the script with some data
    $data = array(
        'foo' => 'bar',
        'baz' => 'qux'
    );
    wp_localize_script( 'mytheme-script', 'my_data', $data );
}
add_action( 'wp_enqueue_scripts', 'mytheme_enqueue_scripts' );

In the example above, we’re using wp_localize_script() to pass a PHP array $data to our my-script.js file. We can then access this data in our JavaScript file like so:

console.log(my_data.foo); // outputs 'bar'
console.log(my_data.baz); // outputs 'qux'

Both wp_add_inline_script() and wp_localize_script() are effective ways to pass variables from PHP to JavaScript in WordPress. The choice of method depends on your specific use case and personal preference.