John Davidson

php - Get subcategories of subcategories

0 comments
Message:


I have my own menu structure in the template. The code below works fine. Here I get the parent category and all the subcategories of that parent category. The problem is that now I need to output another level of nesting.


<?php
$taxonomies = get_terms(array(
'taxonomy' => 'product_cat',
'hide_empty' => true
));

if (!empty($taxonomies)) :
foreach ($taxonomies as $category) {
if ($category->parent == 0) {
$output .= '<div class="menu_item">';
if ($category->parent == 0 && get_term_children($category->term_id, 'product_cat')) {
if ($category->parent == 0) {
$output .= '<div class="parent_item"><a href="' . get_term_link($category) . '">' . $category->name . '</a></div>';
}
$output .= '<div class="sub_menu">';
foreach ($taxonomies as $subcategory) {
if ($subcategory->parent == $category->term_id) {
$output .= '<div class="sub_item"><a href="' . get_term_link($subcategory) . '">' . $subcategory->name . '</a></div>';
}
}
$output .= '</div>';
}
$output .= '</div>';
}
}
echo $output;
endif;
?>

And that's where I broke down). I can't figure out how to get another level of nesting). I get the following result:




<div class="menu_item">

<div class="parent_item">
<a href="#">Parent Menu Item</a>
</div>

<div class="sub_menu">
<div class="sub_item">
<a href="#">Sub Menu Item</a>
</div>

<div class="sub_item">
<a href="#">Sub Menu Item</a>
</div>
</div>

</div>


My Answer:
To add another level of nesting for subcategories of subcategories, you can modify the code as follows:

php
$taxonomies = get_terms(array(
'taxonomy' => 'product_cat',
'hide_empty' => true
));

if (!empty($taxonomies)) :
foreach ($taxonomies as $category) {
if ($category->parent == 0) {
$output .= '';
}
}
echo $output;
endif;


This code will now display the parent category, its subcategories, and the subcategories of those subcategories in a nested structure. You can continue this nesting pattern for as many levels as needed.

Rate this post

3 of 5 based on 4188 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us