0

I want to use a javascript plugin on my website that should be initialized with values set in the wordpress customizer.

Kirki::add_field( 'artist_theme_config', array(
  'type'        => 'select',
  'settings'    => 'gallery_lightgallery_transition',
  'label'       => __( 'Select the transition type of your lightgalleries', 'site-name' ),
  'section'     => 'artist_theme_gallery_style',
  'default'     => 'lg-slide',
  'priority'    => 10,
  'choices'     => array(
    'lg-slide' => esc_attr__( 'Slide', 'site-name' ),
    'lg-fade' => esc_attr__( 'Fade', 'site-name' ),
    'lg-zoom-in' => esc_attr__( 'Zoom In', 'site-name' ),
  ),
) );

My goal is to run the initialization logic with the options set in the customizer. Therfore I need to get the value of the setting in a custom javascript. I found that one way (is it correct?) to get the value is:

wp.customize.instance( 'gallery_lightgallery_transition' ).get();

However that just works if the customizer is open. What is the correct way to get the value of a customizer field in javascript? Do I need to enqueue the script with the correct dependency, like in

wp_enqueue_script('sage/customizer_controls.js', asset_path('scripts/customizer_controls.js'), [ 'customize-controls' ], null, true);

? I do not want to put the logic in the customizer_controls.js however, but in a file called plugins.js. There is a long discussion on how to pass variables from php to javascript in wordpress, however there should be a way with the new customizer api I guess, just can't find any examples or documentation.

1 Answer 1

1

You need to do it the same way you'd get options, shortcodes, or any other WordPress value into JavaScript: You need to get them with PHP and pass them to the script with wp_localize_script():

wp_enqueue_script( 'my-script', asset_path( 'scripts/plugins.js' ), [], null, true );
wp_localize_script(
    'my-script',
    'myScript',
    [
        'galleryTransition' => get_theme_option( 'gallery_lightgallery_transition' ),
    ]
);

Just change my-script and myScript to something specific to your project.

Now you can access the value in your script via myScript.galleryTransition.

2
  • I will check that out, thanks. I thought there would be a way with the new JS customizer API?
    – user9
    Mar 9, 2019 at 14:57
  • Why would there be? The JS Customizer API is for working with controls inside the Customizer. It's got nothing to do with the front end. Any front-end API for working with the Customizer data would either just be doing what I'm doing in my answer, which would be a waste because most Customizer values wouldn't be needed in JS, or would require an AJAX request, which would be slower. Mar 10, 2019 at 2:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.