plugin for wp_list_categories with posts

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

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";
    }
}

Leave a Comment