(更新#2)
Here\'s完整小部件class 我之前通过我的评论分享的内容
因为class, 这个checkbox1 字段默认为未选中,而checkbox 默认情况下会选中字段。
(更新#1。请注意,此更新未使用示例代码,但希望此答案是more 比上一个答案更有用。)
首先,checkbox 字段(即。<input type="checkbox">), 您可能已经知道,通常有两个值&mdash;“开”值(如果checkbox 字段已选中,并且有一个“关闭”值(如果字段为not 已选中)。
假设您有一个具有以下默认选项的小部件checkbox 字段:
$defaults = array(
\'cb1\' => \'yes\',
\'cb2\' => \'no\',
);
对于这两个字段,“on”值为
yes, 而“off”值为
no.
然后在小部件选项表单中,显示checkbox 使用以下标记的字段:(other attributes such as id and name are intentionally not included)
<input type="checkbox" value="{A}"<?php checked( \'{B}\', \'{C}\' ); ?>>
在哪里
{A} 和
{B} 始终为“开”值,而
{C} 是数据库中当前的值
$defaults 数组,如果小部件选项尚未更改&mdash;e、 g.小部件刚刚添加到侧栏。
所以如果你看一下(上面的)样本$defaults 阵列:
在cb1 默认情况下,字段将被选中,因为默认值是“开”值&mdash;$defaults[\'cb1\'] 是yes.
在cb2 字段将是not 默认选中,因为默认值为“关闭”值&mdash;$defaults[\'cb2\'] 是no.
示例小部件class 用于测试checkbox 字段:“我的小部件”
<?php
class MY_Widget extends WP_Widget {
public function __construct() {
parent::__construct( \'my_widget\', \'My Widget\', array(
\'classname\' => \'my-widget\',
\'description\' => \'Testing checkbox fields.\',
) );
}
public function widget( $args, $instance ) {
echo $args[\'before_widget\'];
echo \'<pre>\'; var_dump( $instance ); echo \'</pre>\';
echo $args[\'after_widget\'];
}
public function update( $new_instance, $old_instance ) {
$instance = $old_instance;
$instance[\'cb1\'] = isset( $new_instance[\'cb1\'] ) ? \'yes\' : \'no\';
$instance[\'cb2\'] = isset( $new_instance[\'cb2\'] ) ? \'yes\' : \'no\';
return $instance;
}
public function form( $instance ) {
$instance = wp_parse_args(
(array) $instance,
// The default options.
array(
\'cb1\' => \'yes\', // checked by default
\'cb2\' => \'no\', // not checked by default
)
);
?>
<p>
<input type="checkbox" id="<?php echo $this->get_field_id( \'cb1\' ); ?>" name="<?php echo $this->get_field_name( \'cb1\' ); ?>" value="yes"<?php checked( \'yes\', $instance[\'cb1\'] ); ?>>
<label for="<?php echo $this->get_field_id( \'cb1\' ); ?>">Checkbox #1</label><br>
<input type="checkbox" id="<?php echo $this->get_field_id( \'cb2\' ); ?>" name="<?php echo $this->get_field_name( \'cb2\' ); ?>" value="yes"<?php checked( \'yes\', $instance[\'cb2\'] ); ?>>
<label for="<?php echo $this->get_field_id( \'cb2\' ); ?>">Checkbox #2</label>
</p>
<?php
}
}