This content originally appeared on DEV Community and was authored by Hisman
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.
wp_enqueue_script( 'my-theme-script', get_template_directory_uri() . '/js/script.js' );
wp_add_inline_script( 'my-theme-script', 'var myThemeParams = ' . json_encode( array(
'homeURL' => home_url(),
'themeOptions' => get_theme_mod( 'mytheme_options', false ),
) ), 'before' );
In your JavaScript you can access it like this:
console.log( myThemeParams.homeURL );
console.log( myThemeParams.themeOptions );
This content originally appeared on DEV Community and was authored by Hisman
Hisman | Sciencx (2021-08-29T11:05:45+00:00) How to pass PHP variables to JavaScript in WordPress. Retrieved from https://www.scien.cx/2021/08/29/how-to-pass-php-variables-to-javascript-in-wordpress/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.