One recent post from each category
-
I needed to get a list of recent posts – one from each category and could not find a built-in capabilities, so I created a custom SQL-query:
$wpdb->get_results ( "SELECT posts.ID, terms.term_id FROM $wpdb->posts AS posts JOIN(SELECT MAX(posts.post_date) AS post_date, posts.post_type AS post_type, posts.post_status AS post_status, terms.term_id AS term_id FROM $wpdb->posts AS posts LEFT JOIN $wpdb->term_relationships AS rel ON posts.ID=rel.object_ID LEFT JOIN $wpdb->term_taxonomy AS tax USING(term_taxonomy_id) LEFT JOIN $wpdb->terms AS terms USING(term_id) WHERE posts.post_type='post' AND posts.post_status='publish' AND tax.taxonomy='category' GROUP BY term_id) AS terms USING(post_date, post_type, post_status) ORDER BY post_date DESC" );
Query works fine, but I’m novice to WordPress and ‘ll be grateful to get point to a possible redundancy or errors of the query. Or there may be an easier way?
NOTE: This query recognizes that the post can be simultaneously in multiple categories. For example, if post_1 of 12-Dec in cat_1 and cat_2, and post_2 of 14-Dec in cat_2 and cat_3, output will be cat_1->post_1, cat_2->post_2, cat_3->post_2.
Viewing 10 replies - 1 through 10 (of 10 total)
Viewing 10 replies - 1 through 10 (of 10 total)
- The topic ‘One recent post from each category’ is closed to new replies.