I read the documentation of the codex but i can’t order the get_categories() result just like parent,childrens.
I have these kind of categories’ three:
-Events
- Music
- Culture
- Workshop
- Tourism
-Sport
-Football
-Rugby
-Tennis
I want the output to be:
Events, Music
I tried:
echo $product->get_categories();
and the results is the print of Music, Events (child, parent).
I also tried putting $args as the argument get_categories():
$args = array(
'type' => 'post',
'child_of' => 0,
'parent' => '',
'orderby' => 'name',
'order' => 'ASC',
'hide_empty' => 1,
'hierarchical' => 1,
'exclude' => '',
'include' => '',
'number' => '',
'taxonomy' => 'category',
'pad_counts' => false
);
How can I order it the way I want?
Firstly,
$product->get_categories()
won’t work because it’s a woocommerce function, that basically is just a wrapper forget_the_term_list
, which has no sorting parameter. It’s always good to take a look at the source to know what you’re dealing with.Secondly,
get_the_term_list
usesget_the_terms
, but it also has no sorting parameter. The latter get the terms either from the cacheget_object_term_cache
or directlywp_get_object_terms
. The cache is most likely of no use, because the terms there are saved with the wrong sorting, hence the problem you’re having.wp_get_object_terms
on the other hand has – finally – the ability to define sorting.From the codex:
Usage
Default Arguments
So this could get you closer to what you want, but take a look yourself.
Thirdly, you could just use
get_ancestors
, which gives you back anWhich works fine on the woocommerce product category taxonomy as it is hierarchical. It gets a little bit problematic though if you’re assigning multiple terms per hierarchy level. I’ve wrote an answer concerning this general topic, maybe it’ll help you further.
I wrote this code that I run after get_categories. This will order the results by parent categories and names:
I don’t have a setup like you, so let’s try something. I’m giving the code, you better try and give me the feedback. Is it satisfying?
I tried:
It prints All category grouped for hierarchy, in my case:
I would just to omit the category not selected for the post.