2

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.

1 Answer 1

4

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";
    }
}
1
  • 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
    Commented Jan 19, 2011 at 14:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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