Snippet: Get list of all subcategories

Add following snippet to “functions.php”

Usage

<? echo list_sub_categories(5); ?>

Snippet

function list_sub_categories($cat) {
    $echo = '<ul class="category-"'.$cat.'>' . "\n";
    $childcats = get_categories('child_of=' . $cat . '&hide_empty=1');
    foreach ($childcats as $childcat) {
        if (1 == $childcat->category_parent) {
            $echo .= "\t" . '<li><a href="' . get_category_link($childcat->cat_ID).'" title="' . $childcat->category_description . '">';
            $echo .= $childcat->cat_name . '</a>';
            $echo .= '</li>' . "\n";
        }
    }
    $echo .= '</ul>' . "\n";
    return $echo;
}

Result

This function returns a formatted unordered list of non-empty sub categories of specified category.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>