My WP blog has 12 categories, 80 subcategories.
I need to fetch the latest post from each of those 12 categories.
I know how to do it in 12 queries using 12 get_posts() but is there a way to get them in one query?
I tried to make it work like this but it fetches more than 12 posts:
// Get array of categories (level-0 only).
$cats= array();
$categories=get_categories($args);
foreach($categories as $category) {
if ($category->parent == 0) {
$cats[]= $category->term_id ;
}
}
$categories= implode(',',$cats);
// Fetch the latest post of each category
global $wpdb;
$querystr = "SELECT wposts.*
FROM $wpdb->posts wposts
LEFT JOIN $wpdb->term_relationships ON (wposts.ID = $wpdb->term_relationships.object_id)
LEFT JOIN $wpdb->term_taxonomy ON ($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id)
WHERE $wpdb->term_taxonomy.taxonomy = 'category'
AND $wpdb->term_taxonomy.term_id IN($categories)
ORDER BY wposts.post_date DESC";
$pageposts = $wpdb->get_results($querystr, OBJECT);
And then the loop:
global $post;
foreach ($pageposts as $k=>$post):
setup_postdata($post);
// ... wp loop through your results
}