Wordpress小部件:复选框不保存状态

时间:2014-03-14 19:36:09

标签: wordpress checkbox widget

我有一个带复选框的Wordpress小部件。我正在尝试将默认状态设置为"已选中"通过将我的默认数组中的变量设置为true来选中其中一个复选框。如果我取消选中该框并尝试保存小部件,则复选框将恢复为正在检查,因此基本上我无法取消选中此框。

我有其他具有相同配置的复选框,它们正常工作。有没有人看到我的代码有什么问题?

$defaults = array(
    'widget' => 'cat',
    'type' => 'list',
    'selected' => 0,
    'use_products' => 'true',
    'title' => '',
    'sub_title' => '',
    'operator' => 'IN',
    'print_before_widget' => 'true',
    'print_after_widget' => 'true',
    'hide_empty' => 'true',
    'hide_on_cats' => 'false',
    'custom_class' => ''
);

$instance = parse_args( $instance, $defaults );
extract( $instance );

<p>
<input class="checkbox"
        <?php if ( isset( $use_products ) && $use_products=='true' ) { echo 'checked="checked"'; } ?>
        id = "<?php echo $this->get_field_id( 'use_products' ); ?>"
        name = "<?php echo $this->get_field_name( 'use_products' ); ?>"
        value = "true"
        type = "checkbox"
    />
    <label for="<?php echo $this->get_field_id( 'use_products' ); ?>" ><?php _e( 'Show Product Categories', textdomain ); ?></label>
</p>

1 个答案:

答案 0 :(得分:0)

这里可能有一些问题,但你可能没有提供足够的背景。

我假设这是一个来自您的小部件的form()方法内部的片段。 form()方法传递$ instance变量,该变量包含所有窗口小部件设置的当前值。你似乎根本没有使用它。您对该复选框的值硬编码为true,并且您的$defaults数组未被任何内容合并或覆盖 - 您只需设置默认值并直接使用它们 - 您不使用数据库中的值。

https://codex.wordpress.org/Widgets_API#Default_Usage

编辑


在您的更新方法中,对于复选框,您应该执行以下操作...

public function update($new_instance, $old_instance){

    $instance = array();

    $instance['checkbox_key'] = ( ! empty( $new_instance['checkbox_key'] ) ) ? strip_tags( $new_instance['checkbox_key'] ) : '';

    return $instance;
}

如果在您的上下文中这没有意义,您应该更新您的答案以包含update()方法。

相关问题