How to order the get_categories result

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:

Read More
-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?

Related posts

4 comments

  1. Firstly, $product->get_categories() won’t work because it’s a woocommerce function, that basically is just a wrapper for get_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 uses get_the_terms, but it also has no sorting parameter. The latter get the terms either from the cache get_object_term_cache or directly wp_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

    wp_get_object_terms( $object_ids, $taxonomies, $args )
    

    Default Arguments

    $args = array('orderby' => 'name', 'order' => 'ASC', 'fields' => 'all');
    

    The first argument is called ‘orderby’ and has the default value of ‘name’. Other supported values include ‘count’, ‘slug’, ‘term_group’, ‘term_order’, and ‘term_id’.

    The second argument is called ‘order’ and has the default value of ‘ASC’. The only other value that will be acceptable is ‘DESC’.

    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 an

    Array of ancestors from lowest to highest in the hierarchy

    Which 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.

  2. I wrote this code that I run after get_categories. This will order the results by parent categories and names:

    $all_categories = get_categories( $args );
    
    $byId = array();
    // Create an array with categories by id
    foreach ($all_categories as $cat) {
        $byId[$cat->term_id] = $cat;
    } 
    
    // Add a new path field that we can sort by
    foreach ($all_categories as $cat) { 
        $path = $cat->name;
        $parentCat = $cat;
        for($n=0;$n<10 && $parentCat->parent > 0;$n++) {
            // Limit to 10 levels (change if you need to)
            $parentCat = $byId[$parentCat->parent];
            $path = $parentCat->name."/".$path;
        }
        $cat->path = $path;
    } 
    
    // Finally sort by the new path field
    function cmp($a, $b) {
        return strcmp($a->path,$b->path);
    }
    
    usort($all_categories, "cmp");
    
    // $all_categories are now sorted by hierarchy and name
    
  3. 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?

    <?php
    $args = array(
        'type'                     => 'post',
        'child_of'                 => 0,
        'parent'                   => '',
        'orderby'                  => 'name',
        'order'                    => 'ASC',
        'hide_empty'               => false,
        'hierarchical'             => 1,
        'exclude'                  => '',
        'include'                  => '',
        'number'                   => '',
        'taxonomy'                 => 'category',
        'pad_counts'               => false
    );
    
    $cats = get_categories( $args );
    //var_dump($cat);
    foreach( $cats as $cat ){
        echo $cat->name .', ';
    }
    ?>
    
  4. I tried:

    <?php
    $args = array(
        'type'                     => 'product',
        'child_of'                 => 0,
        'parent'                   => '',
        'orderby'                  => 'term_group',
        'hide_empty'               => false,
        'hierarchical'             => 1,
        'exclude'                  => '',
        'include'                  => '',
        'number'                   => '',
        'taxonomy'                 => 'product_cat',
        'pad_counts'               => false
    );
    
    $cats = get_categories( $args );
    //var_dump($cat);
    foreach( $cats as $cat ){
        echo $cat->name.', ';
    }
    ?>
    

    It prints All category grouped for hierarchy, in my case:

    Events, Sport, Music, Culture, Workshop, Tourism, Football, Rugby, Tennis.
    

    I would just to omit the category not selected for the post.

Comments are closed.