Forums

Limiting number of top-level categories returned by wp_list_categories()? (2 posts)

  1. Trahald
    Member
    Posted 2 years ago #

    How can one limit the number of top-level categories returned by wp_list_categories, without limiting the display of their children? Assuming that one does not know the IDs of the categories, thus using the exclude or include parameters is not an option.

    For instance say there are 8 top-level categories, each with 10 children, and perhaps grandchildren as well. I'd like to limit the number of top-level categories displayed to the first 4 (by the default sort order), and each would still display all their children and grandchildren, if any.

    Can this be done out of the box, or perhaps via a plugin?

  2. MichaelH
    Volunteer
    Posted 2 years ago #

    I don't know that you can get there using wp_list_categories.

    Here's a half-hearted attempt at a solution. It only shows a child/grandchildren and child:

    <?php
    $categories=get_categories('number=4&parent=0&hide_empty=0');
    if ($categories) {
    echo 'Categories';
    foreach ($categories as $category) {
    $cat = $category->term_id ;
    echo '<p> category ' . '<a href="' . get_category_link( $category->cat_ID, 'post_tag' ) . '" title="' . sprintf( __( "View all posts in %s" ), $category->name ) . '" ' . '>' . $category->cat_name.'</a> has ' . $category->count . ' post(s). </p> ';
    $children=get_categories('child_of='.$cat);
    $child_cats ='';
    if ($children) {
    foreach ($children as $child) {
    echo '<p> child ' . '<a href="' . get_category_link( $child->cat_ID, 'post_tag' ) . '" title="' . sprintf( __( "View all posts in %s" ), $child->name ) . '" ' . '>' . $child->cat_name.'</a> has ' . $child->count . ' post(s). </p> ';
    }
    }
    }
    }
    ?>

Topic Closed

This topic has been closed to new replies.

About this Topic