最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

custom post types - How to check if a WP_Query has data

programmeradmin1浏览0评论

I have the following WP_Query, which works great:

<h4>Frequently Asked Questions</h4>

<ul class="faq">

<?php 
    $args = array(
    'post_type' => 'questions',
    'posts_per_page' => '3',                                        
    'tax_query' => array(
        array(
        'taxonomy' => 'types',
        'field' => 'slug',
        'terms' => 'customer-service'
        )
    )
);

$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post(); ?>
<li><a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></li>
<?php endwhile; ?>
</ul>

As you can see, there's a title on the top of the query and I would like to find a way to only show that title if there are values inside the query. If not, in case there are no questions, the title still shows and it looks weird.

Any ideas how can I check if there are values inside a query or not?

Thanks!

I have the following WP_Query, which works great:

<h4>Frequently Asked Questions</h4>

<ul class="faq">

<?php 
    $args = array(
    'post_type' => 'questions',
    'posts_per_page' => '3',                                        
    'tax_query' => array(
        array(
        'taxonomy' => 'types',
        'field' => 'slug',
        'terms' => 'customer-service'
        )
    )
);

$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post(); ?>
<li><a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></li>
<?php endwhile; ?>
</ul>

As you can see, there's a title on the top of the query and I would like to find a way to only show that title if there are values inside the query. If not, in case there are no questions, the title still shows and it looks weird.

Any ideas how can I check if there are values inside a query or not?

Thanks!

Share Improve this question edited Aug 29, 2013 at 14:36 Anigel 1033 bronze badges asked Aug 29, 2013 at 14:35 JohannJohann 8674 gold badges14 silver badges31 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 8

Change it up a bit and use have_posts method to check if there are any results:

<?php 
$args = array(
    'post_type' => 'questions',
    'posts_per_page' => '3',                                        
    'tax_query' => array(
        array(
        'taxonomy' => 'types',
        'field' => 'slug',
        'terms' => 'customer-service'
        )
    )
);

$loop = new WP_Query( $args );
if ($loop->have_posts()){
?>
<h4>Frequently Asked Questions</h4>

<ul class="faq">
    <?php while ( $loop->have_posts() ) : $loop->the_post(); ?>
        <li><a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></li>
    <?php endwhile; ?>
</ul>
<?php }
发布评论

评论列表(0)

  1. 暂无评论