List Categories and Subcategories on the Site - Wordpress

Asked

Viewed 577 times

1

I am currently with a site project, and I have a list of Wordpress taxonomies, so:

-- Engines (parent)

--- Single Phase Motors (son)

--- Three Phase Engines (son)

I wanted to know how to create an HTML list in the Style:

  • Electric Motors
    • Motor Monophasic
    • Three-phase Motor

My Code is currently taking all taxonomies and creating a direct list without Subcategories:

<ul>
    <?php
    $terms = get_terms(array(
        'taxonomy' =>'categoria',
        'hide_empty' => false
    ));

    foreach($terms as $term){  ?>
        <li>
            <div class="menu-link"><a href="?taxonomy=<?= $term -> slug ?>"><?= $term -> name ?> </a><i class="fa fa-chevron-right" aria-hidden="true"></i></div>
        </li>
    <?php 
    } 
    ?>
</ul>

I wanted to get the subcategories through the parent category.

1 answer

0


See if the code below can help you:

<ul>
    <?php
    $terms = get_terms(array(
        'taxonomy' =>'categoria',
        'hide_empty' => false
    ));

    foreach($terms as $term){  ?>
        <li>
            <div class="menu-link"><a href="?taxonomy=<?= $term -> slug ?>"><?= $term -> name ?> </a><i class="fa fa-chevron-right" aria-hidden="true"></i></div>
            <ul>
            <?=
            $term_id = $term->term_id;
            $term_children = get_term_children( $term_id, 'categoria' );
            foreach ( $term_children as $child ) {
                $termC = get_term_by( 'id', $child, $taxonomy_name );
                echo '<li><a href="?taxonomy=<?= $termC->slug ?>">'.$termC->name.'</a></li>';
            }
            ?>
            </ul>
        </li>
    <?php 
    } 
    ?>
</ul>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.