这是我在插件中使用widget的代码:
class shortcodes_widget extends WP_Widget {
function shortcodes_widget() {
parent::WP_Widget(false, $name = __('t', 't') );
}
function form($instance) {
if($instance) {
$title = esc_attr($instance['title']);
$textarea = esc_textarea($instance['textarea']);
$checkbox = esc_attr($instance['checkbox']);
} else {
$title = '';
$textarea = '';
$checkbox = '';
}
?>
<p>
<label for="<?php echo $this->get_field_id('title');?>"><?php _e('t', 't'); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo $title; ?>" />
</p>
<p>
<label for="<?php echo $this->get_field_id('textarea'); ?>"><?php _e('t', 't'); ?></label>
<textarea class="widefat" id="<?php echo $this->get_field_id('textarea'); ?>" name="<?php echo $this->get_field_name('textarea'); ?>"><?php echo $textarea; ?></textarea>
</p>
<p>
<input id="<?php echo $this->get_field_id('checkbox'); ?>" name="<?php echo $this->get_field_name('checkbox'); ?>" type="checkbox" value="1" />
<label for="<?php echo $this->get_field_id('checkbox'); ?>"><?php _e('t', 't'); ?></label>
</p>
<?php
}
function update($new_instance, $old_instance) {
$instance = $old_instance;
$instance['title'] = strip_tags($new_instance['title']);
$instance['textarea'] = strip_tags($new_instance['textarea']);
$instance['checkbox'] = strip_tags($new_instance['checkbox']);
return $instance;
}
public function widget( $args, $instance ) {
extract( $args );
while(isset($textarea)) {
$textarea = $instance['textarea'];
$checkbox = $instance['checkbox'];
}
if(isset($checkbox) and $checkbox == '1') {
echo '<div class="myclass">';
}
else {
echo '<div>';
}
echo $before_widget;
if (isset($instance['textarea'])) {
echo do_shortcode($instance['textarea']);
}
echo $after_widget;
echo '</div>';
}
}
add_action('widgets_init', create_function('', 'return register_widget("shortcodes_widget");'));
问题是:
if(isset($checkbox) and $checkbox == '1') {
echo '<div class="myclass">';
}
else {
echo '<div>';
}
如果选中复选框,它将不会回显第一个值(div和&#34; myclass&#34;)。只回显来自&#34; else&#34;的第二个值。我必须添加isset和while函数以避免PHP通知。
我尝试了一个=而没有引号但没有任何帮助。有帮助吗?
答案 0 :(得分:1)
通过深入了解WordPress核心,学习并获得灵感!以下是默认WP小部件处理控制下拉选项的复选框的方式:
public function widget( $args, $instance ) {
$d = ! empty( $instance['dropdown'] ) ? '1' : '0';
if ( $d ) {
// do stuff
}
}
public function update( $new_instance, $old_instance ) {
$instance = $old_instance;
$instance['dropdown'] = ! empty( $new_instance['dropdown'] ) ? 1 : 0;
return $instance;
}
public function form( $instance ) {
$dropdown = isset( $instance['dropdown'] ) ? (bool) $instance['dropdown'] : false;
?>
<p><input type="checkbox" class="checkbox" id="<?php echo $this->get_field_id('dropdown'); ?>" name="<?php echo $this->get_field_name('dropdown'); ?>"<?php checked( $dropdown ); ?> />
<label for="<?php echo $this->get_field_id('dropdown'); ?>"><?php _e( 'Display as dropdown' ); ?></label><br />
<?php
}