• Hi,
    Can anyone tell me the code to display just 2 of the latest posts from a category please?
    I need to insert it into a panel on the homepage.
    Many thanks,
    Chris

Viewing 3 replies - 1 through 3 (of 3 total)
  • <?php
    $cat_id = get_cat_ID('featured'); //or whatever you want
    $args=array(
      'cat' => $cat_id,
      'post_type' => 'post',
      'post_status' => 'publish',
      'posts_per_page' => 2,
      'caller_get_posts'=> 1
    );
    $my_query = null;
    $my_query = new WP_Query($args);
    if( $my_query->have_posts() ) {
      echo 'List of two Posts in category featured ';
      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().
    ?>
    Thread Starter ckentish

    (@ckentish)

    Thats great – what would the syntax be if I wanted to show 2 posts from 2 categories as well?
    Many thanks for your help.

    See How do I determine a Post, Page, Category, Tag, Link, Link Category, or User ID? to find your two category IDs, then put those IDs in the include parameter below:

    <?php
    //print two posts for each of two selected categories
    $taxonomy = 'category';
    $param_type = 'category__in';
    $term_args=array(
      'include' => '1,2',
      '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' => 2,
          'caller_get_posts'=> 1
          );
        $my_query = null;
        $my_query = new WP_Query($args);
        if( $my_query->have_posts() ) {
          echo 'List of Posts in '.$taxonomy .' '.$term->name;
          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().
    ?>
Viewing 3 replies - 1 through 3 (of 3 total)

The topic ‘Displaying just 2 posts from a category?’ is closed to new replies.