How can I calculate the total number of categories at different hierarchy levels?

This is a bit broad to give you the full code, so ‘I’ll give you an outline. The idea is to loop through all categories and count how many parents each category has using get_term_parents_list (please look carefully what this function returns). This will tell you how deep the level of this category is. Then store the result in a multidimensional array. Like this:

$cat-levels = array(); // multidimensional array in which to store results
$categories = get_categories(); // retrieve an array of all categories (as objects)
foreach ($categories as $category) {
  $parents = get_term_parents_list ($category->ID, 'category');
  $count = // write code to extract amount of parents returned
  $cat-levels[$count][] = $category;
  }

Now $cat-levels[0] will contain all categories without parents, $cat-level[1] will have the categories one level deep. And so on.

Leave a Comment