Site icon Hip-Hop Website Design and Development

WordPress Customizer Selective Refresh: works only on first setting change

I have created a new control (checkbox) in WP Customizer. The way it should work is as it follows: the corresponding section should display the last published post when the checkbox is checked (true) or a custom background image (and some content) when the checkbox is unchecked (false).

Everything works fine on first setting change. Let’s say the input is unchecked on page load – the section will display a custom background image. If I check the checkbox the section refreshes and the last post gets displayed. Until here everything is fine.

But if I uncheck the checkbox (as a second action on same control) nothing happens. Still nothing on next checks/unchecks.

I don’t have any JS related to this control (I’ve also removed all custom JS and the issue persists).

customizer.php

$wp_customize->add_setting( 'latest_post', 
                            array(
                                'default'    => "", 
                                'type'       => 'theme_mod',
                                'capability' => 'edit_theme_options',
                                'transport'   => 'postMessage',
                            ) 
                        );
$wp_customize->add_control('latest_post', 
                            array(
                                'label'    => __( 'Header Content', 'mytheme' ),
                                'section'  => 'header_section',
                                'settings' => 'latest_post',
                                'type'     => 'checkbox'
                            )
                        );      
$wp_customize->selective_refresh->add_partial( 'latest_post', array(
                            'selector'        => '.header-section',
                            'render_callback' => 'header_markup'
                        ) );



function header_markup(){
  $latest_post = get_theme_mod('latest_post');

  switch($latest_post):
     case true:
        return "latest post";
     case false:
        return "custom media";
     default:
        return "custom media";
  endswitch;

}

html

<div class="header-section">
   <php echo header_markup(); ?>
</div>