Wordpress - get_categories hierarchical order like wp_list_categories - with name, slug & link to edit cat

output as unordered list:

<?php

    hierarchical_category_tree( 0 ); // the function call; 0 for all categories; or cat ID  

function hierarchical_category_tree( $cat ) {
    // wpse-41548 // alchymyth // a hierarchical list of all categories //

  $next = get_categories('hide_empty=false&orderby=name&order=ASC&parent=' . $cat);

  if( $next ) :    
    foreach( $next as $cat ) :
    echo '<ul><li><strong>' . $cat->name . '</strong>';
    echo ' / <a href="' . get_category_link( $cat->term_id ) . '" title="' . sprintf( __( "View all posts in %s" ), $cat->name ) . '" ' . '>View ( '. $cat->count . ' posts )</a>  '; 
    echo ' / <a href="'. get_admin_url().'edit-tags.php?action=edit&taxonomy=category&tag_ID='.$cat->term_id.'&post_type=post" title="Edit Category">Edit</a>'; 
    hierarchical_category_tree( $cat->term_id );
    endforeach;    
  endif;

  echo '</li></ul>'; echo "\n";
}  
?>

A slightly updated version of Michael’s answer to use the more generic get_terms (so you can get custom taxonomies, in this case I wanted the WooCommerce product category taxonomy of product_cat).

echo hierarchical_term_tree();

function hierarchical_term_tree($category = 0)
{
    $r = '';

    $args = array(
        'parent' => $category,
    );

    $next = get_terms('product_cat', $args);

    if ($next) {
        $r .= '<ul>';

        foreach ($next as $cat) {
            $r .= '<li><a href="' . get_term_link($cat->slug, $cat->taxonomy) . '" title="' . sprintf(__("View all products in %s"), $cat->name) . '" ' . '>' . $cat->name . ' (' . $cat->count . ')' . '</a>';
            $r .= $cat->term_id !== 0 ? hierarchical_term_tree($cat->term_id) : null;
        }
        $r .= '</li>';

        $r .= '</ul>';
    }

    return $r;
}

Simplified a little to take out the edit link etc. You can add those as required.

Tags:

Categories