Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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
add comment

1 Answer 1

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
add comment

Your Answer

 
discard

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.