我正在使用 WP_Query 循环访问 wordpress 中的自定义帖子类型。我的循环看起来像这样:
<div class="bigRedStrip">
<h2>Available Now!</h2>
</div>
<ul>
<?php $loop = new WP_Query( array( 'post_type' => 'films', 'post_child' => 0, 'posts_per_page' => 8,'orderby' => 'date', 'order' => 'ASC', 'film-categories' => 'blu-ray' ) ); ?>
<?php while ( $loop->have_posts() ) : $loop->the_post(); ?>
<li>
loop stuff here
</li>
<?php endwhile; ?>
</ul>
如您所见,在循环之前有一个 header ,上面写着“现在可用!”。我想重新格式化循环,以便如果没有返回任何帖子,则不会显示包含标题的 div(div 类 bigRedStrip)。我已经尝试了许多潜在的解决方案,但我一直遇到的问题是,所有这些“解决方案”都需要将 <div class="bigRedStrip">
在循环内,这会导致每个返回的帖子都重复标题。这个想法是让标题只显示一次。有什么想法可以实现吗?
最佳答案
你只需要把东西拉开一点。首先运行查询:
<?php $loop = new WP_Query( array( 'post_type' => 'films', 'post_child' => 0, 'posts_per_page' => 8,'orderby' => 'date', 'order' => 'ASC', 'film-categories' => 'blu-ray' ) ); ?>
然后检查是否有东西:
<?php if ($loop->have_posts()) { ?>
<div class="bigRedStrip">
<h2>Available Now!</h2>
</div>
...
如果是这样,只需遍历帖子:
...
<ul>
<?php while ( $loop->have_posts() ) : $loop->the_post(); ?>
<li>
loop stuff here
</li>
<?php endwhile; ?>
</ul>
<?php } ?>
关于php - Wordpress,如果循环没有结果,则不显示标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9852925/