Show X Posts For Y Categories

This code will show X posts per category for Y number of categories.

The Latest Post From Each Category Plugin might work, but has not been updated in a while.

<?php
$num_cats_to_show = 10;
$num_posts_per_cat = 1;
$count = 0;
$taxonomy = 'category';//  e.g. post_tag, category
$param_type = 'category__in'; //  e.g. tag__in, category__in
$term_args=array(
  'orderby' => 'name',
  'order' => 'ASC',
);
$terms = get_terms($taxonomy,$term_args);
if ($terms) {
  foreach( $terms as $term ) {
    $args=array(
      "$param_type" => array($term->term_id),
      'post_type' => 'post',
      'post_status' => 'publish',
      'posts_per_page' => $num_posts_per_cat,
      'caller_get_posts'=> 1
      );
    $my_query = null;
    $my_query = new WP_Query($args);
    if( $my_query->have_posts() ) {
      $count ++;
      if ($count <= $num_cats_to_show) {
        while ($my_query->have_posts()) : $my_query->the_post(); ?>
          <p><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></p>
         <?php
        endwhile;
      }
    }
  }
}
wp_reset_query();  // Restore global post data stomped by the_post().
?>

To select only specific categories, add the ‘include’ parameter to the $term_args array, like this:

$term_args=array(
  'orderby' => 'name',
  'order' => 'ASC',
  'include' => array(23,51,12),  // A list of IDs to include
);

Leave a Reply

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


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>