php - 检查长度 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 事件,我想显示一个段落而不是一些通知
解决方案
只需使用 empty 函数检查数组是否为空。
if (empty($frontPageEvents)) {
echo 'There are no upcoming events';
} else {
while ($frontPageEvents -> have_posts()){
$frontPageEvents -> the_post();
?>
}
如果有的话,不要忘记事件输出后的右括号。
推荐阅读
- javascript - 当数组都是字符串时,如何按整数对数组中的对象进行排序?
- django - Flutter 聊天应用程序,检查 API 中的更改(Django-Rest-Framework)
- multithreading - Akka - 用于阻塞操作的固定线程池 - 阻塞调度程序
- javascript - 承诺中的返回值总是未定义的
- winforms - 为什么关闭表单然后转到变量会导致我的 powershell 崩溃?
- javascript - 里程表计数器值 0 在启动
- javascript - 不允许自定义元素操作自己的子节点吗?
- powershell-v6.0 - Powershell V6.0 中远程计算机获取服务的替代方案
- javascript - chart.js 图例标签的“过滤器”功能永远不会被调用
- c - 为什么这个 C 代码在 macOS 上会产生分段错误,而在其他系统上却不会?