3

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;
  • You must use a loop. Read the codex entry on WP_Query..there's an example loop there. Additionally in the same page you can find the posts_per_page parameter and limit the query to retrieve only 1 post. – helgatheviking Apr 3 '14 at 19:54
  • @helgatheviking Yes I know that it's possible that way, But so it is not possible without the loop? – Robbert Apr 3 '14 at 19:56
  • You can use 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() – Howdy_McGee Apr 3 '14 at 20:05
  • 2
    Try $connected->posts[0]->post_name - $connected is an WP_Query object which contains a posts array member. – user27457 Apr 3 '14 at 20:08
  • Everything is possible, but why reinvent the wheel? var_dump($connected) to see why what you've proposed doesn't work. $connected is actually an object with the resulting posts actually in the $connected->posts property. – helgatheviking Apr 3 '14 at 20:10
7

If 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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