Попытка кодировать пользовательский виджет с тегом множественного выбора в его форме

Я пытаюсь собрать пользовательский виджет "Последние сообщения".
Моя проблема в том, что одно из полей <select multiple> тег категории сообщений, которые пользователь может выбрать. Этот тег выбора, конечно, должен возвращать более одного значения, но мой виджет выводит только самый последний выбранный алфавит категории. Вот мой код, если кто-то так проливает свет. Благодарю.

/////////////////////////////////////////////////////////////////
/////////////////////// CUSTOM WIDGET ///////////////////////////
/////////////////////////////////////////////////////////////////




// Register and load the widget

function wpb_load_widget() {
register_widget( 'di_latest_post_widget' );
}
add_action( 'widgets_init', 'wpb_load_widget' );

 // Creating the widget 

class di_latest_post_widget extends WP_Widget {

function __construct() {
parent::__construct(

// Base ID of your widget

'di_latest_post_widget', 

// Widget name will appear in UI

__('DI - Latest Posts', 'di-news-blog'), 

// Widget description

array( 'description' => __( 'Latest posts widget with custom DI style', 'wpb_widget_domain' ), ) 
);
}

// Creating widget front-end

public function widget( $args, $instance ) {
    $title = apply_filters( 'widget_title', $instance['title'] );
    $numPost = $instance['numPost'];
    $categ = $instance['categ'];


// before and after widget arguments are defined by themes

    echo ($args['before_widget']);
    if ( ! empty( $title ) )
    echo $args['before_title'] . $title . $args['after_title'];

// This is where you run the code and display the output



    $query = new WP_Query(array(
        'post_type'      =>  'post',
        'category_name'      =>  $categ,
        'posts_per_page' => $numPost,
        'ignore_sticky_posts' => true
    )); ?>

        <div class="di-custom-latest">
            <?php if ($query->have_posts()) {
        while($query->have_posts()) {
            $query->the_post();
            get_template_part('di-latest-widget');
      }
    } else {
        echo('<p>'. __('No content found', 'di-news-blog') . '</p>');
    } ?>
        </div>

        <?php 

        wp_reset_postdata();

            echo $args['after_widget'];
        }

  // Widget Backend 

public function form( $instance ) {
    if ( isset( $instance[ 'title' ] ) ) {
        $title = $instance[ 'title' ]; }
    else {
        $title = __( 'Latest Posts', 'di-news-blog' );
    }
    if ( isset( $instance ['numPost'] ) ) {
        $numPost = $instance[ 'numPost' ]; }
    else {
        $numPost = __( 3 , 'di-news-blog' );
    }
    if ( isset( $instance ['categ'] ) ) {
        $categ = $instance[ 'categ' ];
     }
    else {
        $categ = __( 'All categories' , 'di-news-blog' );
    }
    $cats = get_terms(array(
            'taxonomy' => 'category',
            'hide_empty' => false,
    ));

    // Widget admin form

    ?>
    <p>
    <label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title:', 'di-news-blog' ); ?></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 esc_attr( $title ); ?>" />
    <label for="<?php echo $this->get_field_id( 'numPost' ); ?>"><?php _e( 'Number of posts:' , 'di-news-blog' ); ?></label> 
    <input style="margin-top: 15px" class="tiny-text" id="<?php echo $this->get_field_id( 'numPost' ); ?>" name="<?php echo $this->get_field_name( 'numPost' ); ?>" type="number" step="1" min="1" max="10" value="<?php echo esc_attr( $numPost ); ?>" size="3"><br><br>
    <label for="<?php echo $this->get_field_id( 'categ' ); ?>"><?php _e( 'Select categories:' , 'di-news-blog' ); ?></label> 
    <select  multiple style="height:200px" id="<?php echo $this->get_field_id( 'categ' ); ?>" name="<?php echo $this->get_field_name( 'categ' ); ?>">
        <option value="" style="margin-bottom:3px;"><?php _e('All categories', 'di-news-blog') ?></option>
    <?php 
        for ($i=0; $i < count($cats); $i++) { 
            printf(
                    '<option value="%s" class="hot-topic" %s style="margin-bottom:3px;">%s</option>',
                    $cats[$i]->name,
                    in_array( $cats[$i]->name, $categ) ? 'selected="selected"' : '',
                    $cats[$i]->name
            );
        ?>
        <?php } ?>  

    </select>
    </p>

О, и я также не могу понять, почему атрибут selected="selected" не отображается в правом теге option.

РЕДАКТИРОВАТЬ: // РЕШЕНО // Проблема заключалась в простом добавлении [ ] к имени поля выбора, так что это закончилось так:<?php echo $this->get_field_name( 'categ' ); ?>[]

Это работает, даже если я понятия не имею, как работает этот синтаксис. Квадратные скобки после закрывающего тега php???

0 ответов

Другие вопросы по тегам