WP_Query headache

2019-09-02 02:08发布

问题:

I am trying to use WP_Query to output the 3 latest posts with the tag featured. I asked about it here on stackoverflow and got at good tip from a kind person. This is what I have now:

<?php

$home_featured = new WP_Query(array(
    'tag' => 'featured',
    'posts_per_page' => 3,
));

?>

<?php if ($home_featured->have_posts()): while ($home_featured->have_posts()) : $home_featured->the_post(); ?>

    <p>Got some</p>

<?php endwhile; ?>

<?php else: ?>

    <p>None found</p>

<?php endif; ?>

Now, I have 3 posts that have the tag featured. Since Wordpress uses a while loop here, it should do one iteration per post up to 3 times, outputting a

Got some

. This should result in something like this on the screen:

Got some Got some Got some

But it only outputs it one time, like this:

Got some

What is wrong?

回答1:

First thing, replace <p>Got some</p> by <?php the_title(); ?>. At least you'll see what posts are being shown.

You could also do a print_r( $home_featured ); just before starting the wordpress loop. You'll get all the parameters passed to WP_Query, the SQL generated for the query and all the posts that have been returned.

Echoing $home_featured->found_posts will also help you by displaying the total number of posts found matching the current query parameters.