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:
<?php
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
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:
<?php
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
Share Improve this question edited Nov 15, 2018 at 0:41 John Greco asked Nov 15, 2018 at 0:35 John GrecoJohn Greco 51 silver badge5 bronze badges1 Answer
Reset to default 0There 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; ?>