I’m looking to get the depth a category’s subcategories.
Suppose I have a category ‘grandparent’ which has a subcategory ‘parent’ which in turn has a subcategory ‘child’. How do I get to integer 2?
I suppose I could check if ‘grandparent’ has subcategories and if it does, check if they have subcategories, etc, until I hit 0. But that seems like a lot of unnecessary processing.
Isn’t there a more elegant way?
I would do it this way:
- get all sub-categories (include empty, set up hierarchically) as array
- retrieve the depth of the array in PHP (this part is taken (but adapted) from here)
Altogether, it’s the following code, which is bundled into a function, but could, of course, be used directly somewhere in a template file:
function get_category_depth($id = 0) {
$args = array(
'child_of' => $id,
'hide_empty' => 0,
'hierarchical' => 1,
);
$categories = get_categories($args)
if (empty($categories))
return 0;
$depth = 1;
$lines = explode("\n", print_r($categories, true));
foreach ($lines as $line)
$depth = max(
$depth,
(strlen($line) - strlen(ltrim($line))) / 4
);
return ceil(($depth - 1) / 2) + 1;
} // function get_category_depth
Please note that I did not test this.