How can I get the first post from a WP_Query result?
$connected = new WP_Query( array(
// Arguments
));
// This doesn't work..
echo $connected[0]->post_name;
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It only takes a minute to sign up.
Sign up to join this communityIf you poke through WP_Query
the set of queried posts is saved into posts
property and current post gets assigned to post
one (each time loop iterates).
So you could do $connected->posts[0]
if you need to just fetch that, but it might be more convenient to do $connected->the_post();
then $connected->post
if you need to skip first one and process the rest in normal loop.
You may use a code like this:
if ($the_query->have_posts()) {
$first_post = $the_query->posts[0];
echo "1st post title\t:"$first_post->post_title;
}
posts_per_page
parameter and limit the query to retrieve only 1 post.get_post()
Codex or use The Loop like the commentor above suggests, and if you still need the first post you can alwyas rewind your query -$connected->rewind_posts()
$connected->posts[0]->post_name
did the job!