Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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

1 Answer 1

up vote 1 down vote accepted

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">
    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 }
share|improve this answer
    
Thanks @Bainternet, you were totally right! –  Johann Aug 29 '13 at 15:57

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.