简体   繁体   中英

Wordpress Custom Theme: mixing php and javaScript?

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:

  1. Register a script in your theme (usually in your functions.php file). See here: wp_enqueue_script
  2. Localize the script
  3. 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;

prob

var myvariable='<?php echo get_theme_mod("color1");?>';  //note the surrounding ''!

if you are having issues accessing the variable, declare it a global.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM