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

This might be a completely "I'm still new to WP" type question, but I ran into some interesting output when using get_posts() and wp_get_recent_posts() in a custom function I wrote with setup_postdata(). Here's what I had in my functions.php file:

function getRecentPosts($total_posts = 2)
    $total_posts = intval($total_posts);
    global $post;

    $args = array(
        'posts_per_page' => $total_posts,
        'post_type'      => 'post',
        'post_status'    => 'publish'
    $posts = get_posts($args);

    foreach ($posts as $post)
        echo '<div>';
        echo '</div>';

Simple, right? And that function works great, throwing out title's inside div tags perfectly. But when I replace lines 7-12 with the following:

    $args = array(
        'posts_per_page' => $total_posts,
        //'post_type'    => 'post',
        'post_status'    => 'publish'
    $posts = wp_get_recent_posts($args);

...then the function doesn't seem to "iterate" through the posts correctly, throwing out the first post it finds' title over and over, much like if you don't use global $post at the beginning of the function.

Why is this? Is there something different that wp_get_recent_posts() does that I do not yet understand.

share|improve this question
try $posts = wp_get_recent_posts($args, ''); $post global var should be an object. wp_get_recent_posts as default output posts as array. – gmazzap Aug 20 '13 at 11:33
up vote 2 down vote accepted

If you look at the source of setup_postdata() you'll find that it requires an object ($post), to be passed, not an array.

wp_get_recent_posts() (source), by default (for pre 3.1 backwards compatibilty) returns each post as an array. The second, optional argument, that can be passed to wp_get_recent_posts() can prevent this:

$posts = wp_get_recent_posts( $args, OBJECT_K )

(though any value other than ARRAY_A in the second argument will do).

share|improve this answer
Happy to see this is the exact thing I've said in my comment. :) – gmazzap Aug 20 '13 at 11:53
@G.M. Indeed, your comment is the correct answer :) – Stephen Harris Aug 20 '13 at 11:58
Thank you both! I feel like I could've researched this a little better, but I'm learning something new every day! :) – Chris Kempen Aug 22 '13 at 7:35
@Chris - If in doubt, just check the source :). queryposts.com is incredibly useful for that. (Second only to a decent IDE). – Stephen Harris Aug 22 '13 at 10:18
@StephenHarris Oh wooooow O__O ! Clearly I'm still learning! ;) – Chris Kempen Aug 23 '13 at 19:25

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.