Search code examples
wordpressloopscategoriesposts

Custom parent category and subcategory


I really need your help. i just created a WordPress page template that display all the post but my problem is the display of the custom parent taxonomy/category and it's children. My post look like this.

    <table>
  <tr>
    <td>Title</td>
    <td>Parent Category</td>
    <td>Sub Category</td>
    <td>Excerpt</td>
  </tr>
  <tr>
    <td>a title</td>
    <td>USA custom category</td>
    <td>Hawaii uder USA</td>
    <td>this is a sample description.</td>
  </tr>
   </table>

My only problem is to display the sub category. Anyone can help me?

This is my code on how i display the parent custom category:

 <?php

    $term_list = '';
    $terms     = get_the_terms( $post->ID, 'origincity' );
    foreach( $terms as $term ) {
        $parent_term = get_term( $term->parent, 'origincity' );
        $term_list  .= $parent_term->name ;
    }
    echo $term_list;
   ?>

I tried to display the sub category by this code :

<?php $terms2 = wp_get_post_terms($post->ID, 'origincity', array("fields" => "all"));

foreach ($terms2 as $term1) {
    echo $term1->name.'<br>';
} ?>

but it also return the parent. :(

Your help is highly appreciated. Thanks.


Solution

  • Already solve the problem by this code:

    function print_taxonomic_ranks( $terms ){
    
    
        // set id variables to 0 for easy check 
        $order_id = $family_id = $subfamily_id = 0;
    
    
        // get family
        foreach ( $terms as $term ) { 
            if ( $family_id || $order_id != $term->parent )
                continue;
            $family_id = $term->term_id;
            $family    = $term->name;
        }
    
        // get subfamily
        foreach ( $terms as $term ) { 
            if ( $subfamily_id || $family_id != $term->parent ) 
                continue;
            $subfamily_id = $term->term_id;
            $subfamily    = $term->name;
        }
    
        // output
        echo "$subfamily";
    
    }
    

    Thanks by the way.