0

I want to watch a customizer setting so that when its value changes, it updates value of another field (all stored in 'option', not theme mods).

  • Setting field: header_style
  • When header_style is changed, I want to auto change value of header_nav_type.

Note: PHP only solution please as I am looking for a hook. I already figured out how to do it using the JS API. However, to keep things DRY, I have to do it on PHP side.

1 Answer 1

1

This is very easy to do. What you want to do is hook into the customize_save_after action hook - https://developer.wordpress.org/reference/hooks/customize_save_after/ - and check your setting and based on it update another. Example:

add_action( 'customize_save_after', function() {

    // Get the setting you want to retrieve value from
    $new_value_setting_1 = get_theme_mod( 'SETTING_ID' );

    // Update another setting
    if ( $new_value_setting_1 ) {
        set_theme_mod( 'SETTING_ID', $new_value_setting_1 );
    }

    // Delete theme mod if setting is empty rather then storing an empty value
    else {
        remove_theme_mod( 'SETTING_ID', $new_value_setting_1 );
    }

} );

So whenever the customizer settings are changed the other setting is updated. Unfortunately doing it in the Customizer when the setting is changed won't be possible without JS (from what I know) if you want to do it with PHP you should be hooking into customize_save_after.

That is unless...if the setting you are checking for uses the refresh method so when it's modified the Customizer window refreshes, then you can hook into init to change the value..like this:

add_action( 'init', function() {

    // Only needed in the customizer
    if ( ! is_customize_preview() ) {
        return;
    }

    // Get the setting you want to retrieve value from
    $new_value_setting_1 = get_theme_mod( 'SETTING_ID' );

    // Update another setting
    if ( $new_value_setting_1 ) {
        set_theme_mod( 'SETTING_ID', $new_value_setting_1 );
    }

    // Delete theme mod if setting is empty rather then storing an empty value
    else {
        remove_theme_mod( 'SETTING_ID', $new_value_setting_1 );
    }

} );

I hope this helps!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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