Hi why don’t you used multiple check-box instead of select option field. As well as you have used deprecated functions like “create_function”. I have modified your code which replaced select option with multiple check-box selection.
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;
}
}
Hope it will help to solved your problem. 🙂