Come verificare se una WP_Query ha dati

29 ago 2013, 17:35:08
Visualizzazioni: 19.3K
Voti: 5

Ho la seguente WP_Query, che funziona perfettamente:

<h4>Domande Frequenti</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>

Come puoi vedere, c'è un titolo sopra la query e vorrei trovare un modo per mostrarlo solo se ci sono valori all'interno della query. Altrimenti, nel caso non ci siano domande, il titolo viene comunque visualizzato e sembra strano.

Qualche idea su come posso verificare se ci sono valori all'interno di una query o meno?

Grazie!

0
Tutte le risposte alla domanda 1
0

Modificalo leggermente e utilizza il metodo have_posts per verificare se ci sono risultati:

<?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>Domande Frequenti</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