主题定制器:默认复选框值问题

时间:2017-04-17 作者:Oni-Link

我的主题定制器中的复选框控件的默认值有问题。该控件的默认值为true,但当我检查该值时,get\\u theme\\u mod()总是返回false。

准确地说:如果我转到主题定制器并保存该值(true或false,无所谓),它将开始正常工作。但如果我不手动保存该选项至少一次,我就无法正确检索默认值。

这是我的代码:

$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\'
        )
      )
    );
这是自定义控件声明,如果这有帮助的话:

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
        }
    }
我错过什么了吗?

非常感谢。

1 个回复
最合适的回答,由SO网友:Aristeides 整理而成

如果没有使用get\\u theme\\u mod()函数的第二个参数在其中添加默认值,那么它将始终返回false,除非该值在自定义程序中发生更改。解决方案很简单。。。始终在get\\u theme\\u mod中使用默认值。

相关推荐