WordPress Tricks: Displaying the most recent posts from several different categories

Here is the code that I use to display the latest posts from certain categories on a regular WordPress page. Copy and paste this block of code into the template file where you want to display the posts:

 

<h3>Latest posts</h3><br/>
<?php
//for categories 1,5,3, show 1 post
$cat_args=array(
  'include' => '1,5,3',
  'orderby' => 'name',
  'order' => 'ASC'
   );
$categories=get_categories($cat_args);
  foreach($categories as $category) {
    $args=array(
      'showposts' =>3,
      'category__in' => array($category->term_id),
      'caller_get_posts'=>1
    );
    $posts=get_posts($args);
      if ($posts) {
        echo '<p><h4>Latest <a href="' . get_category_link( $category->term_id ) . '" title="' . sprintf( __( "View all posts in %s" ), $category->name ) . '" ' . '>' . $category->name.' Posts</a>: </h4></p> ';
        foreach($posts as $post) {
          setup_postdata($post); ?>
          <p style="margin-left:20px;">
<a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></p>
          <?php
        } // foreach($posts
      } // if ($posts
    } // foreach($categories
?>

 

You can control which order the posts are displayed in by changing the parameters ‘orderby’ and ‘order’. Visit http://codex.wordpress.org/Template_Tags/get_posts to learn more about controlling the posts that are displayed.

You can change the number of posts that are displayed by changing the number after ‘showposts.’

If you have any issues with this or questions on how to use it or change, just leave a comment or submit your question on the WordPress coding help page.

Related Posts:

  • No Related Posts

One Response to “WordPress Tricks: Displaying the most recent posts from several different categories”

  1. [...] Here is the code that I use to display the most recent posts from specific categories on a WordPress page: [...]

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> <pre lang="" line="" escaped="" highlight="">