question might seem dumb but i truly didn't find helpfull links so im trying to do a simple query where i select the latest 10 posts and i want to be able to show only 1 post from those 10 in loop
my code looks like
// Query latest 10 records
$the_query = new WP_Query( array(
'post_type' => 'post',
"order" => "DESC",
'posts_per_page' => 10,
'orderby' => 'modified',
) );
For loop
if ( $the_query->have_posts() ) :
while ( $the_query->have_posts() ) : $the_query->the_post();
$featured_img_url = get_the_post_thumbnail_url(get_the_ID(),'full');
<?php the_title(); ?>
endwhile;
wp_reset_postdata();
endif;
question might seem dumb but i truly didn't find helpfull links so im trying to do a simple query where i select the latest 10 posts and i want to be able to show only 1 post from those 10 in loop
my code looks like
// Query latest 10 records
$the_query = new WP_Query( array(
'post_type' => 'post',
"order" => "DESC",
'posts_per_page' => 10,
'orderby' => 'modified',
) );
For loop
if ( $the_query->have_posts() ) :
while ( $the_query->have_posts() ) : $the_query->the_post();
$featured_img_url = get_the_post_thumbnail_url(get_the_ID(),'full');
<?php the_title(); ?>
endwhile;
wp_reset_postdata();
endif;
Share Improve this question asked Apr 14, 2020 at 0:18 SamSam 114 bronze badges 1- which one of the 10 posts do you want to show? – Michael Commented Apr 14, 2020 at 0:57
1 Answer
Reset to default 0Assuming you want to keep the WP_Query exactly the same there's 2 ways I can think of which you could do this using various loops.
1) Grab the first post from the posts
Array.
WP_Query has a bunch of properties and methods one of which is the posts
array.
if( $the_query->have_posts() ) {
// Grab the first post object
$single_post = $the_query->posts[0]; // $post is reserved by global.
// This only gives you access to object properties, not `the_*()` functions.
echo $singe_post->post_title;
}
// Overwrite the global $post object
if( $the_query->have_posts() ) {
// Grab the global post
global $post;
$post = $the_query->posts[0]; // Grab the first post object.
setup_postdata( $post ); // Allows you to use `the_*()` functions. Overwrites global $post
the_title();
// Reset global $post back to original state
wp_reset_postdata();
}
2) Rewind the query when necessary.
The following will loop through the loop as normal but at the end we'll rewind it. This ensures that should we want to loop through all the posts, it will include the first post. This method uses WP_Query::rewind_posts
if( $the_query->have_posts() ) {
while( $the_query->have_posts() ) {
$the_query->the_post();
// Break out of the loop after displaying 1 post.
if( $the_query->current_post >= 1 ) {
break;
}
the_title();
}
// Rewind the posts back to index 0, or the beginning.
$the_query->rewind_posts();
// Always call after running a secondary query loop that uses `the_post()`
the_query->wp_reset_postdata();
}