views:

274

answers:

2

Hi

I am new to Wordpress and been pulling my hair out trying to create a category loop. The loop is supposed to:

  1. loop through all categories
  2. echo out the category name (with link to
  3. echo out the last 5 posts in that category (with permalink to post)

The html for each would be

<div class="cat_wrap">
   <div class="cat_name">
       <a href="<?php get_category_link( $category_id ); ?>">Cat Name</a>
   </div>
   <ul class="cat_items">
      <li class="cat_item">
         <a href="permalink">cat item 1</a>
      </li>
      <li class="cat_item">
         <a href="permalink">cat item 2</a>
      </li>
      <li class="cat_item">
          <a href="permalink">cat item 3</a>
      </li>
      <li class="cat_item">
         <a href="permalink">cat item 4</a>
      </li>
      <li class="cat_item">
         <a href="permalink">cat item 5</a>
      </li>
   </ul>
</div>

Please help

+2  A: 

Hy keeping things simple here is how you can solve it

<?php wp_list_categories('show_count=1&title_li=<h2>Categories</h2>'); ?>
streetparade
Yep, use wp_list_categories and in Settings-Reading, set your "Blog pages show at most " to 5.
Michael
+1  A: 

Oops, missed that you wanted 5 posts

<?php
//for each category, show 5 posts
$cat_args=array(
  'orderby' => 'name',
  'order' => 'ASC'
   );
$categories=get_categories($cat_args);
  foreach($categories as $category) { 
    $args=array(
      'showposts' => 5,
      'category__in' => array($category->term_id),
      'caller_get_posts'=>1
    );
    $posts=get_posts($args);
      if ($posts) {
        echo '<p>Category: <a href="' . get_category_link( $category->term_id ) . '" title="' . sprintf( __( "View all posts in %s" ), $category->name ) . '" ' . '>' . $category->name.'</a> </p> ';
        foreach($posts as $post) {
          setup_postdata($post); ?>
          <p><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
?>
Michael