What if you need to display the grandchildren categories from a known category? In this tutorial I will show you one way to browse through categories with get_categories and list the names of the grandchildren categories on a page.
Here is the hierarchy on categories we have and we want to display grandchildren category 1 and grandchildren category 2.
First we need to know the id of the “first level category”. To do this mouse over the “first level category” and look at the bottom left of your browser – there should be the link to the category. Look for the parameter value of tag_ID – this is your category id.
Let’s do some coding now. We will use get_categories with some arguments: parent to indicate the parent category and
//getting the child categories of parent 2
$args = array(
'parent' => 2,
'taxonomy' => 'category',
'hide_empty' => 0
);
$categories = get_categories($args);
Next, we should read the $categories values in a foreach:
foreach ( $categories as $category ) {
}
Let’s get the grandchildren details. To do this, we will put another set of args and get_categories inside the foreach. We will simply set the args to get the categories that have parents in the foreach.
foreach ( $categories as $category ) {
//setting up the args where the parents are the child categories
$grandchildrenargs=array(
'parent' => $category->term_id, //this reads the child category id and looks for subcategories
'taxonomy' => 'category',
'hide_empty' => 0
);
$grandchildrencategories = get_categories($grandchildrenargs);
}
The last thing to do now is to make another foreach that goes through the $grandchildrencategories values. Here is the complete code:
//getting the child categories of parent 2
$args = array(
'orderby' => 'name',
'parent' => 2,
'taxonomy' => 'category',
'hide_empty' => 0
);
$categories = get_categories($args);
foreach ( $categories as $category ) {
//setting up the args where the parents are the child categories
$grandchildrenargs=array(
'parent' => $category->term_id,
'taxonomy' => 'category',
'hide_empty' => 0
);
$grandchildrencategories = get_categories($grandchildrenargs);
foreach ( $grandchildrencategories as $grandchildrencategory ) {
//getting the grandchildren ids or whatever else is needed and populating the array
echo '';
}
}