There is many ways to pass dynamic variables to JavaScript. An easy way would be just to define the JavaScript variables in the <head> echoing the PHP variables.
This will of course work, but there is a WordPress-way to do it as well.
The function wp_localize_script gives you the ability to write a JavaScript object with multiple variables defined. The function must be called after your script has been enqueued. Simply pass in the name of your script handle, the object name and your data.
function mytheme_wp_enqueue_scripts() { wp_enqueue_script( 'mytheme_script', get_template_directory_uri() . '/js/main.js', array('jquery'), false, true ); wp_localize_script( 'mytheme_script', 'myObj', array( 'homeUrl' => home_url(), 'translatableString' => __( 'A String' ) ) ); } add_action( 'wp_enqueue_scripts', 'mytheme_wp_enqueue_scripts' );
This will print the following code before your script is included
<script type='text/javascript'> /* <!--[<span class="hiddenSpellError" pre=""-->CDATA[ */ var myObj = {"homeUrl":"http:\/\/forsakringskassan.dev","translatableString":"A String"}; /* ]]> */ </script>
Then you are free to use the variable in your JavaScript in which ever way you want!
alert(myObj.translatableString)
That’s all — Happy coding!
[…] Using PHP variables in JavaScript with wp_localize_script « WordPress Quick Tips […]
it’s broken on wp 3.4.1
“An easy way would be just to define the JavaScript variables in the echoing the PHP variables.” WOW that’s all I needed… I’ve spend like 5 hours trying to get the worthless localize script working in WordPress… Even following WordPress’s own tutorial and not changing anything it didn’t work. I have no idea why it needs to be so complicated…
But thank you for that tip at the beginning! It’s the only thing I’ve been able to get to work in the least, thank you so much!