WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

How can I select the first/last object from the list returned by get_posts()?

How can I select the preceding/following object relative to an arbitrary object in the object list returned by get_posts?

How can I extract a sublist from the list returned by get_posts()?

share|improve this question
up vote 1 down vote accepted

This sounds like more of PHP question than a WordPress one - get_posts() just returns an array of objects; interact with them like you would any other numerical array:

$posts = get_posts();

$first_post = $posts[0];
$last_post = array_slice( $posts, -1, 1 );

$everything_but_first_last = array_slice( $posts, 1, -1 );

Check out the complete list of array functions.

share|improve this answer
Thanks for the list. For some reason I can only reference by index the first eight objects, even though print_r($objects); prints them all out (all 123 objects), as does a foreach loop. I get Undefined offset: 8 for index 8 and other higher that I've tried. Any ideas why? – seron Aug 6 '12 at 15:56
My code was bad. I can now reference any index. – seron Aug 6 '12 at 18:52
The list of PHP array functions was very useful. I found answers to my questions using that and some examples I found on the web. In particular, I used array_keys combined with array_search to get the preceding/following object inspired by this Stack Overflow post link – seron Aug 18 '12 at 6:42

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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