At the moment I am writing a little PHP script for myself and my WordPress website. However, I am struggling to set and read the terms for my posts.
For example (this is just a short excerpt) those are my terms:
- Term1
- Sub-term1
- Sub-Sub-term1
- Sub-Sub-Sub-term1
- Sub-term2
- Sub-term3
- Sub-Sub-term1
- Term2
- Sub-term4
- Sub-Sub-term2
And those two cases I have which I have to cover:
-
I want to set the term e.g.
Sub-Sub-Sub-term1
by slug. This is pretty easy and already working for me. I just do it by executing this line:wp_set_object_terms($post_id, $my_term_id, $my_term_field, true);
-
And this is the most difficult part: I want to read the terms but in the order they are selected. So e.g. the term
Sub-Sub-Sub-term1
is selected, all the superterms above are selected too. So, I want to get an array returned, where the first index is the most superterm, in this case it would beTerm1
, on index 1 in the array should be the termSub-term1
and so on and so on. But in addition to that I want the term id, the term name and the term slug to be returned..The problem I am facing now is that I don't know how do order the terms... However, I already know how to get all the terms set for a post:
wp_get_object_terms($post_id, $my_term_field);
This returns an array with all terms as an object but also with all the stuff I don't need. So, for e.g. description and all the other fields. I just need the term id, the term name and the term slug.
All in all, I don't know how to order the terms I get returned.. Do you guys have an idea on how to do this? I mean, there has to be a relation somehow cause WordPress is showing them as children of each superterm and they are also indented in the frontend!
I would appreciate any kind of help! Thank you!