Get Bottom Most Level Taxonomy Terms?

How can I get the bottom-most level terms for a custom taxonomy?Taxonomy Hierarchy example,Custom Taxonomy: "produc

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.

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.

Share Improve this question asked Jun 9, 2019 at 13:05 Deepak SinghDeepak Singh 1488 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745413723a4626650.html

相关推荐

  • Get Bottom Most Level Taxonomy Terms?

    How can I get the bottom-most level terms for a custom taxonomy?Taxonomy Hierarchy example,Custom Taxonomy: "produc

    3小时前
    40

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信