嗨,为什么不使用多个复选框而不是选择选项字段呢。此外,您还使用了不推荐使用的函数,如“create\\u function”。我修改了您的代码,将选择选项替换为多个复选框选择。
function myCatWidget() {
register_widget( \'my_custom_cat_widget\' );
}
add_action( \'widgets_init\', \'myCatWidget\' );
class my_custom_cat_widget extends WP_Widget {
function __construct() {
parent::__construct(\'my_custom_cat_widget\', __(\'My cat widget\', \'wpb_widget_domain\'),
array( \'description\' => __( \'Your description\', \'wpb_widget_domain\' ), )
);
}
public function form( $instance ) {
$title = isset($instance[ \'title\' ]) ? $instance[ \'title\' ] : \'Categories\';
$instance[\'postCats\'] = !empty($instance[\'postCats\']) ? explode(",",$instance[\'postCats\']) : array();
?>
<p>
<label for="<?php echo $this->get_field_id( \'title\' ); ?>">Title</label>
<input type="text" class="widfat" id="<?php echo $this->get_field_id( \'title\' ); ?>" name="<?php echo $this->get_field_name( \'title\' ); ?>" style="width: 100%;" value="<?php echo $title; ?>"/>
</p>
<p>
<label for="<?php echo $this->get_field_id( \'postCats\' ); ?>"><?php _e( \'Select Categories you want to show:\' ); ?></label><br />
<?php $args = array(
\'post_type\' => \'post\',
\'taxonomy\' => \'category\',
);
$terms = get_terms( $args );
//print_r($terms);
foreach( $terms as $id => $name ) {
$checked = "";
if(in_array($name->name,$instance[\'postCats\'])){
$checked = "checked=\'checked\'";
}
?>
<input type="checkbox" class="checkbox" id="<?php echo $this->get_field_id(\'postCats\'); ?>" name="<?php echo $this->get_field_name(\'postCats[]\'); ?>" value="<?php echo $name->name; ?>" <?php echo $checked; ?>/>
<label for="<?php echo $this->get_field_id(\'postCats\'); ?>"><?php echo $name->name; ?></label><br />
<?php } ?>
</p>
<?php
}
public function update( $new_instance, $old_instance ) {
$instance = $old_instance;
$instance[ \'title\' ] = strip_tags( $new_instance[ \'title\' ] );
$instance[\'postCats\'] = !empty($new_instance[\'postCats\']) ? implode(",",$new_instance[\'postCats\']) : 0;
return $instance;
}
public function widget( $args, $instance ) {
extract( $args );
$title = apply_filters( \'widget_title\', $instance[ \'title\' ] );
$postCats = $instance[ \'postCats\' ];
$categories_list = explode(",", $postCats);
echo $before_widget;
if( $title ) {
echo $before_title . $title . $after_title;
}
$args = array(\'post_type\' => \'post\',\'taxonomy\' => \'category\',);
$terms = get_terms( $args );
?>
<ul>
<?php
foreach ($categories_list as $cat) {
foreach($terms as $term) {
if($cat === $term->name) {
echo "<li>".$term->name."</li>";
}
}
}
?>
</ul>
<?php
echo $after_widget;
}
}
希望这将有助于解决您的问题。:)