How to show 6 posts from each category on index page

March 9th, 2009 Posted in Wordpress

Difficulty Level:

dif_low

On this tutorial I will show you how to make this on your wordpress index page:

cat_view

If you wish to show a defined number of posts from each category on your index page, you can do it like this:

  1. <?php
  2. global $post;
  3. $categories = get_categories();
  4. foreach ($categories as $category) {
  5. $cat_id = $category->cat_ID;
  6. $games = get_posts('numberposts=6&orderby=rand&category='.$cat_id);
  7. if ($games) {
  8. echo '<div class="category">';
  9. echo '<h1><a href="'.get_category_link($cat_id).'">' \
  10. .$category->name. '</a></h1>';
  11. foreach ($games as $post) {
  12. ?>
  13. <div class="game_title">
  14. <a href="<?php the_permalink() ?>" rel="bookmark"  \
  15. title="<?php the_title(); ?>" >
  16. <?php if ((strlen($post->post_title) > 10)) { \
  17. echo substr($post->post_title, 0, 10).".."; } else the_title(); ?>
  18. <br>
  19. <img src = "<?php echo get_post_meta($post->ID, "thumbnail_url", \
  20. true);
  21. ?>" width="85" height="85"></a>
  22. </div>
  23. <?php
  24. }
  25. echo '<div class="cat_link"><a href="'.get_category_link($cat_id).'">
  26. \ More Games</a></div>';
  27. echo '</div>';
  28. }
  29. }
  30. ?>

Explanation:

  • Get all categories: “$categories = get_categories(); “
  • Go trough each category and get 6 random posts: “foreach ($categories as $category)” … “get_posts(‘numberposts=6&orderby=rand&category=’.$cat_id);”
  • Get each post and show it: “foreach ($games as $post)” …

You can download this example here:

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • MisterWong
  • Y!GG
  • Webnews
  • Digg
  • del.icio.us
  • StumbleUpon
  • Reddit

Comments are closed.

My-Guide Interessante Guides: Snowboard GuideNewsTutorialsMontenegroSerbien