首页 > 解决方案 > 检查长度 WP_Query(array())

问题描述

大家好,如果以下查询没有结果,我正在尝试显示一些信息。就像是<P> There are no upcoming Events</p>

我如何检查数组的长度以了解它是否包含帖子

这是代码

<?php
                $now = date('Ymd');
                $frontPageEvents = new WP_Query(array(
                  'posts_per_page' => 2,
                  'post_type' => 'event',
                  'meta_key' => 'event_date',
                  'orderby' => 'meta_value_num',
                  'order' => 'ASC',
                  'meta_query' => array(
                    array(
                      'key' => 'event_date',
                      'compare' => '>=',
                      'value' => $now,
                      'type' => 'numeric'
                    )
                  )


                ));


                  while ($frontPageEvents -> have_posts()){
                    $frontPageEvents -> the_post();

                    ?>


                    <div class="">
                      <div class="">
                        <div class=""> <?php
                        $date = new DateTime(get_field('event_date'));
                         echo $date->format('d');
                        ?> <br> <?php echo $date->format('M'); ?></div>

                      </div>
                      <div class="">
                        <img class=""src="<?php the_post_thumbnail_url('eventFrontThumbnail') ?>" alt="">
                      </div>
                      <div class="">
                        <div class="">
                          <h3> <?php the_title(); ?></h3>
                        </div>
                        <div class=""><?php echo wp_trim_words(get_the_content(),10); ?></div>


                        <div class=""> <p>

                          <a class="btn btn-primary"href="<?php the_permalink(); ?>">read more...</a>
                        </p>
                        </div>
                      </div>

                    </div>
                  <?php } ?>

所以之前

while ($frontPageEvents -> have_posts()){
                    $frontPageEvents -> the_post();

                    ?>

如果没有 upcoimg 事件,我想显示一个段落而不是一些通知

标签: phpwordpress

解决方案


只需使用 empty 函数检查数组是否为空。

if (empty($frontPageEvents)) {
    echo 'There are no upcoming events';
} else {
        while ($frontPageEvents -> have_posts()){
               $frontPageEvents -> the_post();
  ?>

}如果有的话,不要忘记事件输出后的右括号。


推荐阅读