Solution:1
The “WordPress way” would be to localize the script.
Utilize wp_localize_script
Overview:
- Register a script in your theme (usually in your functions.php file). See here: wp_enqueue_script
- Localize the script
- Then, access that value via your javascript.
Minimal complete example (compiled from WP docs):
PHP:
add_action('wp_enqueue_scripts', 'my_theme_scripts');
function my_theme_scripts() {
// Register the script first.
wp_register_script( 'some_handle', 'path/to/myscript.js' );
// Now we can localize the script with our data.
$color_array = array( 'color1' => get_theme_mod('color1'), 'color2' => '#000099' );
wp_localize_script( 'some_handle', 'object_name', $color_array );
// The script can be enqueued now or later.
wp_enqueue_script( 'some_handle' );
}
Javascript (in your ‘myscript.js’ file);
// Access the color via the object name defined in localize_script
var color = object_name.color1;