Check if category is child of another
-
12-12-2019 - |
Question
I know how to check what the parent category id is, but what I am trying to do is find out if the current category is a child of a specific category, up to 2 levels deep.
For example: if user is browsing child2 in category1/child1/child2, detecting if child2 is a child of category1
Is there a function that handles this?
Or
should I create a helper with an iterator that climbs up the tree?
Solution
You can pull the path of the current category:
$path = $category->getPath();
The path contains the location in the category tree of the current category separated by a /
. You can do the following to iterate through each category in the path to search for the one you are interested in as being a parent:
$path = explode('/', $path);
array_pop($path); // throw away the current category
array_pop($path); // throw away the parent category
$gparent = array_pop($path); // this is the category you are interested in
If you want to search any category in the tree for the particular parent you could just use a foreach loop:
$path = explode('/', $path);
array_pop($path); // throw away the current category
array_shift($path); // throw away the highest level category which is always 1 (and you don't even see in the tree)
foreach ($path as $p):
if ($p == $gparent):
// do something here
endif;
endforeach;