Get subcategories of subcategories

Viewed 49

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>

And need to end up with something like this:

<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 class="2sub_item">
                <a href="#">2 Sub Menu Item</a>
                <a href="#">2 Sub Menu Item</a>
                <a href="#">2 Sub Menu Item</a>
            </div>

        </div>

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

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

        </div>
    </div>

</div>

0 Answers
Related