Multiple selection for wordpress widget

Question

I created my own category selection widget. So i used <select> but i want to use with multiple attribute.

Here is my widget class. It works perfect without multiple attr. But i want to use it. And it must be return category ids in array.

<?php

class myCatWidget extends WP_Widget {

    function myCatWidget() {
        parent::WP_Widget( false, $name = 'My cat widget' );
    }

    function form( $instance ) {
        $title = esc_attr( $instance[ 'title' ] );
        $postCats = $instance[ 'postCats' ];
        ?>

        <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' ); ?>">Categories</label>
            <select name="<?php echo $this->get_field_name( 'postCats' ); ?>" id="<?php echo $this->get_field_id( 'postCats' ); ?>" style="width: 100%;" multiple>
                <?php
                $args = array(
                    'taxonomy' => 'category',
                );

                $terms = get_terms( $args );
                foreach( $terms as $term ) { ?>
                    <option <?php selected( $instance[ 'postCats' ], $term->term_id ); ?> value="<?php echo esc_attr( $term->term_id ); ?>">
                        <?php echo esc_html( $term->name ); ?>
                    </option>
                <?php } ?>
            </select>
        </p>

        <?php

    }

    function update( $new_instance, $old_instance ) {
        $instance = $old_instance;

        $instance[ 'title' ] = strip_tags( $new_instance[ 'title' ] );
        $instance[ 'postCats' ] = esc_sql( $new_instance[ 'postCats' ] );
        return $instance;
    }

    function widget( $args, $instance ) {
        extract( $args );

        $title = apply_filters( 'widget_title', $instance[ 'title' ] );
        $postCats = $instance[ 'postCats' ];

        echo $before_widget;

        if( $title ) {
            echo $before_title . $title . $after_title;
        }

        echo $postCats;

        echo $after_widget;
    }
}

add_action( 'widgets_init', create_function( '', 'return register_widget("myCatWidget");' ) );

?>
0
bilimokur 3 months 0 Answers 16 views 0

Leave an answer