I am building a custom wordpress theme and I am trying to add some JavaScript functions.
The main function I want to add is a div that changes color over time. The colors it changes to are defined by the theme color settings in the Customize register. I have added those color settings boxes as show below through my functions.php:
$wp_customize->add_setting('color1', array('default' => '#000000', 'transport'=>'refresh',));
$wp_customize->add_control(new WP_Customize_Color_Control($wp_customize, 'color1_CNTL', array(
'label' => __('Color 1', 'myTheme'),
'section' => 'colors',
'settings' => 'color1',)));
all of that works fine and I can use it in the Customize register on my admin page. Now, the only thing I’m wondering is, how do I use the value of color 1 in my javaScript code? I know that if I wanted to use it in css I would just have to use
<?php echo get_theme_mod('color1'); ?>
but that doesn’t work in JavaScript. Any ideas?
The “WordPress way” would be to localize the script.
Utilize wp_localize_script
Overview:
file). See here:
wp_enqueue_script
Minimal complete example (compiled from WP docs):
PHP:
Javascript (in your ‘myscript.js’ file);
prob
if you are having issues accessing the variable, declare it a global.