I am currently using this code in order to get the latest three posts of my website, successfully and with no issues:

$posts = get_posts( array( 'numberposts' => 3 ) );

but I want to switch to wp_query.

I tried a simple wp_query call in order to show tha latest 3 articles posted on my website:

$args = array(
'posts_per_page' => 3
$posts = new WP_Query( $args );

And also used this PHP code in order to provide an output of this wp_query:

while ($posts -> have_posts()) : $posts -> the_post();
foreach( $posts as $p ): ?>
<?php the_title(); ?><br>
<?php endforeach; endwhile; ?>

But in the end it failed. Instead of having an output list of:

First post title
Second post title
Third post title

I do get an output list of:

First post titleFirst post titleFirst post titleSecond post titleSecond post titleSecond post titleThird post titleThird post titleThird post title

1 Answer 1


There shouldn't be a foreach loop inside the while. The while loops over posts, so you don't need another foreach. The while loop in this context is what WordPress calls "The Loop".

See the section of documentation for The Loop on secondary queries here.

So your loop should look like this:

<?php while ( $posts->have_posts() ) : $posts->the_post(); ?>
    <?php the_title(); ?><br>
<?php endwhile; ?>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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