[http://codex.wordpress.org/Function_Reference/wp_localize_script] [http://stackoverflow.com/questions/6808221/php-within-js-file-wordpress]
<?php wp_localize_script( $handle, $name, $data ); ?>
- Register the script
- Create variables in a (preferably associative) array
- Localize the script (handle-of-registered-script-in-step-1,object-name-to-be-used-in-the-JS,the-array-that-contains-the-data-variables)
- Enqueue the registered script in step 1
- Use the object's properties in your JS
functions.php or
plugins/your_plugin.php
<?php
// Register the script first.
wp_register_script( 'discount_vars', get_template_directory_uri() . 'js/scripts.js' );
// Localize the script with our data that we want to use
$options = get_option( 'hub_settings' );
$discount = array('discount1'=> $options['hub_text_field_0'],'discount_2'=> $options['hub_text_field_1'],'discount_3'=> $options['hub_text_field_2'],'discount_4'=> $options['hub_text_field_3']);
wp_localize_script( 'discount_vars', 'discount', $discount );
// The script can be enqueued now or later.
wp_enqueue_script( 'discount_vars' );
?>
scripts.js
alert(discount.discount1); // Will output the 1st textfield option saved in the WP admin custom options page