最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

terms - Order custom taxonomy hierarchy

programmeradmin0浏览0评论

I have some custom taxonomy for regions.

Commonly it would look something like this.

USA (parent)
- Arizona (child 1)
- - Phoenix (child 2)

however, there will be cases where it will only be like

USA
- Arizona

or

UK
- Wales

and maybe even just

Japan

In my for loop I get the taxonomy data as $location = get_the_terms( $id, 'listings_region' );

and then in the html/php I can simply write $location[0]->name and then I get the the name of the first object in the array.

I have however noticed that the taxonomy comes back not in the correct hierarchy - instead, alphabetically.

When I echo '<pre>'; print_r($location); echo '</pre>', I get the array and [0] would be Arizona and [1] would be USA.

How can I retrieve it the taxonomy array in the correct order so that ideally [0] is always the parent, [1] is the first child, etc?

Thanks in advance.

I have some custom taxonomy for regions.

Commonly it would look something like this.

USA (parent)
- Arizona (child 1)
- - Phoenix (child 2)

however, there will be cases where it will only be like

USA
- Arizona

or

UK
- Wales

and maybe even just

Japan

In my for loop I get the taxonomy data as $location = get_the_terms( $id, 'listings_region' );

and then in the html/php I can simply write $location[0]->name and then I get the the name of the first object in the array.

I have however noticed that the taxonomy comes back not in the correct hierarchy - instead, alphabetically.

When I echo '<pre>'; print_r($location); echo '</pre>', I get the array and [0] would be Arizona and [1] would be USA.

How can I retrieve it the taxonomy array in the correct order so that ideally [0] is always the parent, [1] is the first child, etc?

Thanks in advance.

Share Improve this question asked Oct 15, 2019 at 3:49 Ronald LangeveldRonald Langeveld 1052 bronze badges 2
  • wp_list_categories() can help you achieve that hierarchical display. – Sally CJ Commented Oct 15, 2019 at 5:59
  • yes, but i need it to return in an array, just like get_the_terms does. – Ronald Langeveld Commented Oct 15, 2019 at 6:22
Add a comment  | 

2 Answers 2

Reset to default 0

Got it working,

$location = wp_get_post_terms($id, 'listings_region', array('orderby'=> 'parent'));

I basically understand that you want to display all the categories with corresponding child-categories. You can do this by following code:

$terms = get_the_terms($id, 'listings_region');
foreach($terms as $key => $term){
    if($term->parent != 0){
        $terms[$term->parent]->children[] = $term;
        unset($terms[$key]);
    }
}

Not tested own so you need to print it once to get it your way but, need to change approach to access the category and it's child.

发布评论

评论列表(0)

  1. 暂无评论