Forums

[resolved] Show all categories and related posts with the loop (3 posts)

  1. Rajven
    Member
    Posted 1 year ago #

    Hi!
    I want to customize the homepage but I'm not sure if what I want to do it's possible within the loop (or within wordpress).
    I want to show a number of divs equal to the number of categories: every div will have the title of the category (perhaps the description) and the last post of that category (with minor details).
    Is it possible to do this within the loop, or the loop serves only for the post and not for the categories and I have to use another approach like put in some variables information by wp_list_categories-like templates/functions?

    Thanks

  2. alchymyth
    The Sweeper
    Posted 1 year ago #

    http://codex.wordpress.org/Function_Reference/get_categories
    something like:

    <?php  $cats = get_categories(); //use parameters if neccessary
    
    foreach ($cats as $cat) :
    
    echo '<div class="category-post">'; //add more details if you need individual css for each category
    
    $args = array(
    'posts_per_page' => 1, // max number of post per category
    'cat' => $cat->term_id
    );
    query_posts($args); 
    
    if (have_posts()) :
    $num_of_posts = $wp_query->post_count;
    echo '<h2>'.$cat->name.'</h2>';
    
    while (have_posts()) : the_post(); // show whatever you need in the loop, following is example only: ?>		
    
    <div <?php post_class(); ?> >
    <h2><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></h2>
    <div class="entry"><?php the_excerpt(); ?></div>
    </div>
    
    <?php endwhile; ?>
    
    <?php else :
    echo '<h2>No Posts for '.$cat->name.' Category</h2>';
    endif; //end of loop
    wp_reset_query(); ?>
    
    <?php
    echo '</div> <!--end of div.category-post-->';
    endforeach; ?>
  3. Rajven
    Member
    Posted 1 year ago #

    Perfect!!! This was very useful! Thank you very very much =)

Topic Closed

This topic has been closed to new replies.

About this Topic