[wp-hackers] Pull Latest Post from Each of 6 Categories

Nathan Rice ncrice at gmail.com
Tue May 5 04:35:04 GMT 2009


On Mon, May 4, 2009 at 10:42 PM, Austin Matzko <if.website at gmail.com> wrote:


> I would do something like this, where 1-6 are the category ids:
>
> $post_ids = array(0);
> foreach( array(1, 2, 3, 4, 5, 6) as $cat_id ) {
>        if ( $posts = get_posts(array('cat' => $cat_id, 'showposts' => 1)) )
> {
>                $first = array_shift($posts);
>                $post_ids[] = $first->ID;
>        }
> }
> query_posts(array('post__in' => $post_ids));
>
> This has the advantage of using the WordPress API, so you can remain
> agnostic about future database schema changes and take advantage of
> the built-in caching. You can also use the regular Loop following this
> code.
>
>
This is another potentially dumb question, but is the get_posts() function
any less taxing on the database than the WP_Query class?  If it is less
taxing, then you absolutely found and answer that I think may work for me!

But, after looking at the source of that function, it looks like it
establishes it's own new WP_Query object:

$get_posts = new WP_Query;
return $get_posts->query($r);

That would mean I'd be using WP_Query 6 times, PLUS the final loop query.
Seems even less efficient than what I have now.

Am I wrong? If so, again, blame it on my complete lack of knowledge of SQL,
and feel free to correct me. I'm nothing if not teachable.

Nathan


More information about the wp-hackers mailing list