By Deepak Singh


2019-06-09 13:05:13 8 Comments

How can I get the bottom-most level terms for a custom taxonomy?

Taxonomy Hierarchy example,

Custom Taxonomy: "product-category"

Top Level Terms -> Second Level Terms -> Third Level Terms -> Bottom most Level Terms

I want to get only Bottom most level taxonomy terms. I want to get this on out of the loop on index.php page, so setting parent id is not possible in get_terms() function.

1 comments

@Deepak Singh 2019-06-11 14:51:04

Here is the solution I ended up with. This may help others too.

$taxonomy = "product-category";

    $args = array(
        'taxonomy' => $taxonomy,
        'orderby' => 'name',
        'order' => 'ASC',
        'hierarchical'  => true,
        'hide_empty' => false,
    );

    $the_query = new WP_Term_Query($args);
    $categories = $the_query->get_terms();


    if ($categories){

        foreach($categories as $category){
            $ancestors = get_ancestors( $category->term_id, $taxonomy );
            $category->ancestors = $ancestors; 
            $category->depth = count( $ancestors ) ;

            if($category->depth === 3) :    

                echo $category->term_id . '-' . $category->depth . '-' . $category->name;   

            endif; 
        }   

    }   

First, I used WP_Term_Query Class to create the terms object and build my custom query then get_terms() to retrieve all the terms.

Inside foreach loop used get_ancestors() function to return the array containing the parents of the given object and $category->depth to get the current depth.

Related Questions

Sponsored Content

7 Answered Questions

[SOLVED] Get the the top-level parent of a custom taxonomy term

1 Answered Questions

[SOLVED] Custom Taxonomy Only Showing Top Level Terms in Admin?

6 Answered Questions

[SOLVED] Inserting terms in an Hierarchical Taxonomy

1 Answered Questions

Get link for taxonomy to show top-level terms

2 Answered Questions

[SOLVED] Get second level terms of custom taxonomy

4 Answered Questions

[SOLVED] How can I get only parent terms?

1 Answered Questions

Excluding top level from taxonomy and post loop

2 Answered Questions

[SOLVED] Get terms within a custom taxonomy

  • 2013-08-22 16:52:57
  • Jake Lisby
  • 383 View
  • 0 Score
  • 2 Answer
  • Tags:   terms

2 Answered Questions

[SOLVED] How do I get the top-level terms in a custom taxonomy?

  • 2011-01-30 23:43:11
  • Jackson
  • 10853 View
  • 8 Score
  • 2 Answer
  • Tags:   custom-taxonomy

1 Answered Questions

Sponsored Content