Search code examples
wordpresscustom-post-typetaxonomycustom-taxonomytaxonomy-terms

Get children category of a taxonomy by parent id


I have a custom post type "project" with a taxonomy "taxoproject"and I have a template page "template-project.php" with a query loop to display my post.

In this loop I need to display each category associated with the post.

This is my code :

<ul>
   <?php
     $terms = get_the_terms($post->ID, 'taxoproject');
     foreach($terms as $term) { ?>

         <li>
            <?php echo $term->name; ?>
         </li>

     <?php }
   ?>
</ul>

My code works perfectly with one exception, I wish to display only the children of a specific parent of this taxonomy (id 76) and I do not know how to proceed.

Thanks for your help


Solution

  • I found the solution to my problem :

    <ul>
        <?php
            $taxonomy = 'taxoproject'; // Taxonomy slug.
            $terms = get_the_terms( $post->ID, $taxonomy );
    
            $children = '';
    
            foreach ( $terms as $term ) {
                if( $term -> parent == 76 ) { // Parent ID 
                    $children = $term->name; ?>
    
                    <li><?php echo $children; ?></li>
    
                <?php } 
            }
        ?>
    </ul>
    

    Thank you all for the help !