There are several ways to create HTML list of categories.
Default CSS selectors
Simplest way is to display a list of categories with wp_list_categories() and style the output with default CSS selectors:
li.categories
li.cat-item
li.cat-item-7
li.current-cat
li.current-cat-parent
ul.children
The Walker_Category class
The Walker
class is for traversing the hierarchical data like menus or categories. It is an abstract class that has four abstract methods start_el()
, end_el()
, start_lvl()
, end_lvl()
. It is not required to override all abstract methods of the class, only those methods that are needed.
$args = array( 'hide_empty' => false, 'walker' => new MyWalker(), 'title_li' => false );
wp_list_categories( $args );
class MyWalker extends Walker_Category {
function start_el( &$output, $category, $depth = 0, $args = array(), $id = 0 ) {
$output .= '<a href="' . get_category_link( $category->term_id ) . '" >' . $category->name . '</a><br/>';
}
function end_el( &$output, $page, $depth = 0, $args = array() ) {}
function start_lvl( &$output, $depth = 0, $args = array() ) {
$output .= '<ul class="span-5 colborder list_main">'.PHP_EOL;
}
function end_lvl( &$output, $depth = 0, $args = array() ) {
$output .= '</ul>'.PHP_EOL;
}
}
Recursive Function is also a good way to traverse through categories. This way you have to manually get the categories on each node. Since the get_categories() function returns all the children categories in all subnodes, id of the current category must be passed on to be able to display only the current level categories.
get_the_categories();
function get_the_categories( $parent = 0 )
{
$categories = get_categories( "hide_empty=0&parent=$parent" );
if ( $categories ) {
echo '<ul class="span-5 colborder list_main">';
foreach ( $categories as $cat ) {
if ( $cat->category_parent == $parent ) {
echo '<a href="' . get_category_link( $cat->term_id ) . '" >' . $cat->name . '</a><br/>';
get_the_categories( $cat->term_id );
}
}
echo '</ul>';
}
}