Using php inside javascript in wordpress
Take a look at wp_localize_script
. Although ostensibly for translation, it lets you pass PHP values to JS. Here's a fairly good walkthrough on how to use it.
EDIT:
First, ensure that you are loading your JS using wp_enqueue_script
, as you will need to refer to the handle. In your functions.php
you'd have:
$date = get_option('director_date');wp_enqueue_script('my-script', get_stylesheet_directory_uri() . 'js/my-script.js');wp_localize_script('my-script', 'my_script_vars', array( 'date' => $date ));
wp_localize_script
takes three arguments:
- The handle of he script to pass the variables object to. This should match the handle being used in
wp_enqueue_script
- The name of the variable object you want to create. You will use this name to refer to the object in JS
- The array of variable to pass to the object. Here I'm just passing the
$date
variable we declared earlier, but you can obviously pass whatever you want.
Then in my-script.js
, you'd access this object very simply:
var $date = my_scripts_vars.date;alert($date); // Or do whatever you want with it
In index.php
, you can do something like:
<?php $date = get_option('director_date'); ?><script type="text/javascript">var generated_date = '<?php echo $date; ?>';</script>
Just make sure you do this before you include the JavaScript where you want to reference the generated_date
variable you just created.