Show Latest Post From Each of Specified Categories

The Code below illustrates how to select the latest Post from each of a list of categories.

<?php

// Get latest post from a set of categories
$cat_ids = '32,96,1111111';  // list of comma-separated category ids

// These functions and add_filters could go in your functions.php file
function mam_posts_fields ($fields) {
   global $mam_global_fields;
   // Make sure there is a leading comma
   if ($mam_global_fields) $fields .= (preg_match('/^(\s+)?,/',$mam_global_fields)) ? $mam_global_fields : ", $mam_global_fields";
   return $fields;
}
function mam_posts_where ($where) {
   global $mam_global_where;
   if ($mam_global_where) $where .= " $mam_global_where";
   return $where;
}
add_filter('posts_fields','mam_posts_fields');
add_filter('posts_where','mam_posts_where');

$mam_global_fields = ", $wpdb->term_relationships.term_taxonomy_id";
$mam_global_where = " AND post_date =
   (SELECT MAX(p.post_date)
   FROM $wpdb->posts p, $wpdb->term_relationships tr
   WHERE p.ID = tr.object_id
   AND tr.term_taxonomy_id = $wpdb->term_relationships.term_taxonomy_id
   AND p.post_type = 'post'
   AND p.post_status = 'publish'
   AND p.post_date < NOW() ) ";

$cats = explode(',', $cat_ids);
$args = array(
   'cat' => $cat_ids,
   'posts_per_page' => count($cats),
   'ignore_sticky_posts' => 1,
);
query_posts($args);

if (have_posts()) {
   while (have_posts()) {
      the_post();
      // Put your code here to display the posts
      echo "<h2> TAX:$post->term_taxonomy_id "; the_title(); echo "</h2>";
   }
} else {
   // Put your code here for no posts found
}

?>

Leave a Reply

Your email address will not be published. Required fields are marked *

*