Your English is fine. I’m sorry if I sounded critical, that was not my intent. I know English has many quirks. I was hoping to clarify one of those quirks that no one would expect non-native speakers to know.
So your posts do have all the terms assigned. It will be difficult to properly manage the order when wp_list_categories() is used. I know it’s useful to have formatted output done for you but in the end this function will not serve you well. Once you have the list sorted correctly, you should format the output with your own code.
What needs to happen is the $terms array in your code needs to be sorted in descending order of the parent property of each object. This can be done using PHP’s usort() function. This means writing your own comparison function. Your function will be passed two term objects. It needs to compare the parent
and term_id
properties of each and return an appropriate value based on the result of that comparison.
Since the two terms passed may not be immediately related, the comparison can get involved. If one term’s parent is the term_id of another, a result can be returned immediately. If not, the parent of one of the terms needs to be retrieved and that term’s parent compared against the other term’s ID. If no match, continue the same process until a match or parent == 0 is reached. When 0 is reached, we know the other term is not an ancestor, so it must be a descendant and a result can be returned.
Because you want a descending list, the return value will be the reverse of what is normally expected. If that gets too confusing, you can return conventional ascending results, then reverse the array before output with array_reverse(). Your comparison function should allow for the possibility two terms have the same parent. This should not happen, but mistakes can happen when the terms are assigned.
To avoid the need to continually make queries to get parent terms, your main function should create a lookup array of parent IDs keyed by the term’s ID. Declare this array global so that it can be accessed from within the comparison function. Many coders simply hate using globals. I generally agree, but the alternatives here are even worse.
I hope you are able to make sense of all of that. I did warn in my initial reply that this would be tricky ?? You will find in the end the code is not so bad. Grasping the concept and getting it into code is the tricky part. If you need any clarification on any of this, just ask. I’ll do my best to explain.