0

I have a problem with the default value of a checkbox control, in my Theme Customizer. The control has true as default value, but get_theme_mod() always returns me false, when I check that value.

To be precise: if I go to the Theme Customizer and save the value (true or false, it doesn't matter) it starts working correctly. But if I don't manually save the option at least once, I can't retrieve the default value correctly.

Here's my code:

$wp_customize->add_setting(
    'grid_show_cats',
    array(
        'default' => true,
        'sanitize_callback' => 'theme_sanitize_checkbox'
      )
    );

$wp_customize->add_control(
    new Theme_Toggle_Checkbox_Custom_Control(
      $wp_customize,
      'grid_show_cats', array(
          'label' => esc_html__( "Show categories", "theme" ),
          'type' => 'checkbox',
          'settings' => 'grid_show_cats',
          'section' => 'grid'
        )
      )
    );

And this is the custom control declaration, if this may help:

class Theme_Toggle_Checkbox_Custom_Control extends WP_Customize_Control {
        public $type = 'toogle_checkbox';
        public function enqueue(){
            wp_enqueue_style( 'custom_controls_css', get_template_directory_uri() . '/assets/css/custom_controls.css' );
        }
        public function render_content(){
            ?>
            <div class="checkbox_switch">
                <span class="customize-control-title onoffswitch_label"><?php echo esc_html( $this->label ); ?></span>
                <div class="onoffswitch">
                    <input type="checkbox" id="<?php echo esc_attr($this->id); ?>" name="<?php echo esc_attr($this->id); ?>" class="onoffswitch-checkbox" value="<?php echo esc_attr( $this->value() ); ?>" <?php $this->link(); checked( $this->value() ); ?>>
                    <label class="onoffswitch-label" for="<?php echo esc_attr($this->id); ?>"></label>
                </div>
                <p><?php echo wp_kses_post( $this->description ); ?></p>
            </div>
            <?php
        }
    }

Am I missing something?

Thank you.

0

If you don't add a default value in the get_theme_mod() function by using it's 2nd argument then it will always return false unless that value has changed in the customizer. The solution is simple... ALWAYS use a default value in get_theme_mod.

  • Well, I had totally forgotten that get_theme_mod() accepts a second argument. Thank you. – Oni-Link Apr 21 '17 at 17:55

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.