Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

Is there a parameter that can be passed to wp_list_categories, to get a certain number of posts from each category? Or a plugin that does something like that? A similar question was in the Wordpress support forum, but it doesn't do exactly what I want.

share|improve this question

1 Answer 1

up vote 2 down vote accepted

The code that thread links to seems very close to what you are describing - looping through categories and retrieving some amount of posts for each.

If you want to integrate posts into wp_list_categories() you can do that by extending Walker_Category class and using it as custom walker passed via walker argument... but it's not pretty for nested categories (I just tried and it seems to be messy to accurately insert posts).

Some example code, I am not entirely sure it handles nesting properly:

wp_list_categories( array(
    'walker' => new Walker_Category_Posts(),
) );

class Walker_Category_Posts extends Walker_Category {

    function start_el(&$output, $category, $depth, $args) {

        $this->category = $category;

        parent::start_el($output, $category, $depth, $args);
    }

    function end_el(&$output, $page, $depth, $args) {
        if ( 'list' != $args['style'] )
            return;

        $posts = get_posts( array(
            'cat' => $this->category->term_id,
            'numberposts' => 3,
        ) );

        if( !empty( $posts ) ) {

            $posts_list = '<ul>';

            foreach( $posts as $post )
                $posts_list .= '<li><a href="' . get_permalink( $post->ID ) . '">'.get_the_title( $post->ID ).'</a></li>';

            $posts_list .= '</ul>';
        }
        else {
            $posts_list = '';
        }

        $output .= "{$posts_list}</li>\n";
    }
}
share|improve this answer
3  
Bear in mind this isn't going to be efficient, it's essentially performing at least one query per category, which to some degree is unavoidable(but it's something to note). Put it this way, you'd not want something like this on your home page if you're calling lots of categories unless you want to start eating through lots of server resources from the numerous queries that are now running every time someone lands on your main page. –  t31os Jan 19 '11 at 14:17

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.