【问题标题】:Wordpress, if no results from loop, don't show headerWordpress,如果循环没有结果,则不显示标题
【发布时间】:2012-04-08 19:45:25
【问题描述】:

我正在使用 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>

如您所见,在循环之前有一个标题,上面写着“现在可用!”。我想重新格式化循环,因此如果没有返回帖子,则不会显示包含标题(div 类 bigRedStrip)的 div。我尝试了许多潜在的解决方案,但我一直遇到的问题是,所有这些“解决方案”都需要将 &lt;div class="bigRedStrip"&gt; 放入循环中,这会导致每个返回的帖子都重复标题。这个想法是让标题只显示一次。有什么想法可以做到这一点吗?

【问题讨论】:

    标签: php wordpress loops conditional


    【解决方案1】:
    <?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 } ?>
    

    【讨论】:

    【解决方案2】:

    你只需要把这些东西拉开一点。首先运行查询:

    <?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 } ?>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-30
      • 2019-10-08
      • 1970-01-01
      • 2013-10-22
      • 2013-02-19
      • 1970-01-01
      • 2014-06-04
      • 1970-01-01
      相关资源
      最近更新 更多