我正在学习WordPress小部件API。除了复选框控件外,其他一切看起来都很好。此外checked()
函数让我有点困惑,如果我必须默认复选框未选中,我不知道应该建议什么值。
下面是我正在小部件类包装器中尝试的代码。
public function widget( $args, $instance ) {
extract( $args );
$checkbox1 = ! empty( $instance[\'checkbox1\'] ) ? $instance[\'checkbox1\'] : false;
$checkbox2 = ! empty( $instance[\'checkbox2\'] ) ? $instance[\'checkbox2\'] : false;
$checkbox3 = ! empty( $instance[\'checkbox3\'] ) ? $instance[\'checkbox3\'] : false;
echo $args[\'before_widget\'];
echo "Hello world, just testing this out.";
echo $args[\'after_widget\'];
}
public function form( $instance ) {
$defaults = array(
\'checkbox1\' => true,
\'checkbox2\' => true,
\'checkbox3\' => true,
);
$instance = wp_parse_args( (array) $instance, $defaults );
?>
<p>
<input
class="checkbox"
id="<?php echo esc_attr( $this->get_field_id( \'checkbox1\' ) ); ?>"
name="<?php echo esc_attr( $this->get_field_name( \'checkbox1\' ) ); ?>"
type="checkbox"
<?php checked( \'1\', $instance[\'checkbox1\'] ); ?>
value="1">
<label for="<?php echo esc_attr( $this->get_field_id( \'checkbox1\' ) ); ?>">
<?php _e( \'Checkbox #1\', \'test\' ); ?>
</label>
</p>
<p>
<input
class="checkbox"
id="<?php echo esc_attr( $this->get_field_id( \'checkbox2\' ) ); ?>"
name="<?php echo esc_attr( $this->get_field_name( \'checkbox2\' ) ); ?>"
type="checkbox"
<?php checked( \'1\', $instance[\'checkbox2\'] ); ?>
value="1">
<label for="<?php echo esc_attr( $this->get_field_id( \'checkbox2\' ) ); ?>">
<?php _e( \'Checkbox #2\', \'test\' ); ?>
</label>
</p>
<p>
<input
class="checkbox"
id="<?php echo esc_attr( $this->get_field_id( \'checkbox3\' ) ); ?>"
name="<?php echo esc_attr( $this->get_field_name( \'checkbox3\' ) ); ?>"
type="checkbox"
<?php checked( \'1\', $instance[\'checkbox3\'] ); ?>
value="1">
<label for="<?php echo esc_attr( $this->get_field_id( \'checkbox3\' ) ); ?>">
<?php _e( \'Checkbox #2\', \'test\' ); ?>
</label>
</p>
<?php
}
public function update( $new_instance, $old_instance ) {
$instance = $old_instance;
$instance[\'checkbox1\'] = isset( $new_instance[\'checkbox1\'] ) ? 1 : false;
$instance[\'checkbox2\'] = isset( $new_instance[\'checkbox2\'] ) ? 1 : false;
$instance[\'checkbox3\'] = isset( $new_instance[\'checkbox3\'] ) ? 1 : false;
return $instance;
}
感谢您的时间:)