Mittwoch, 20. März 2013

Query wordpress posts by id and return array of entire post objects

Caused me some headache. I had to query posts inside a wordpress extension by their id and return an array of the corresponding post objects. At the moment this is the best solution I found for the problem, even if the code doesn't clearly state what I am doing:

    query_posts(array('post__in' => $this->postids, 'post_type'=> ''));
    $posts = array();

    while (have_posts()) {
        the_post();
        $posts[] = get_post(get_the_ID());
    }

    wp_reset_query();
    return $posts;

So first we query the posts by id. Then we start with the loop and use get_post() to get the post. get_post() sadly doesn't return the current post by default, so we have to pass it the id of the current post (this is so stupid). Once we pass the id it returns a post object which we store inside the $posts array which is returned at the end of the method.

Check http://codex.wordpress.org/Function_Reference/get_post, you might also return the posts as an numeric / associative array instead of an object if you like.