Cómo verificar si un WP_Query tiene datos

29 ago 2013, 17:35:08
Vistas: 19.3K
Votos: 5

Tengo la siguiente WP_Query, que funciona perfectamente:

<h4>Preguntas Frecuentes</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>

Como puedes ver, hay un título en la parte superior de la consulta y me gustaría encontrar una manera de mostrar ese título solo si hay valores dentro de la consulta. Si no hay preguntas, el título aún se muestra y se ve raro.

¿Alguna idea sobre cómo puedo verificar si hay valores dentro de una consulta o no?

¡Gracias!

0
Todas las respuestas a la pregunta 1
0

Cambia un poco y usa el método have_posts para verificar si hay resultados:

<?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>Preguntas Frecuentes</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 }
29 ago 2013 17:39:12