skip to Main Content

I’ve modified a function I found to do what I need, although it works, unfortunately the results returned are not in any specific order, I need them to be alphabetical.

This script returns a list of subcategories from Woocommerce:

function get_product_subcategories_list( $category_slug ){
    $terms_html = array();
    $taxonomy = 'product_cat';
    // Get the product category (parent) WP_Term object
    $parent = get_term_by( 'slug', $category_slug, $taxonomy );
    // Get an array of the subcategories IDs (children IDs)
    $children_ids = get_term_children( $parent->term_id, $taxonomy );

    // Loop through each children IDs
    foreach($children_ids as $children_id) {
        $term = get_term( $children_id, $taxonomy ); // WP_Term object
        $term_link = get_term_link( $term, $taxonomy ); // The term link
        $thumbnail_id   = get_woocommerce_term_meta( $term->term_id, 'thumbnail_id', true );

        if ( is_wp_error( $term_link ) ) $term_link = '';
        // Set in an array the html formatted subcategory name/link
        $terms_html[] = '<li><a href="' . esc_url( $term_link ) . '">' . $term->name . '</li></a>';
    }
    return '<ul>' . implode( $terms_html ) . '</ul>';
}

…and not that it matters, but this is in my template:

get_product_subcategories_list( $post->post_name );

The problem is that $terms_html[] is returning this…

<li><a href="https://example.com/pants">Pants</a></li>
<li><a href="https://example.com/shoes">Shoes</a></li>
<li><a href="https://example.com/hats">Hats</a></li>

…but I need it to be alphabetical like this:

<li><a href="https://example.com/hats">Hats</a></li>
<li><a href="https://example.com/pants">Pants</a></li>
<li><a href="https://example.com/shoes">Shoes</a></li>

2

Answers


  1. Since get_term_children doesn’t provide any way of sorting. Just treat the array with the sorting yourself.

    Push the ->name in the array as key pairs. Then just utilize ksort(). Like so:

    foreach($children_ids as $children_id) {
        $term = get_term( $children_id, $taxonomy ); // WP_Term object
        $term_link = get_term_link( $term, $taxonomy ); // The term link
        $thumbnail_id   = get_woocommerce_term_meta( $term->term_id, 'thumbnail_id', true );
    
        if ( is_wp_error( $term_link ) ) $term_link = '';
        // Set in an array the html formatted subcategory name/link
        $terms_html[$term->name] = '<li><a href="' . esc_url( $term_link ) . '">' . $term->name . '</li></a>';
        //          ^^ push the term name as key
    }
    
    ksort($terms_html); // sort it
    return '<ul>' . implode( $terms_html ) . '</ul>';
    
    Login or Signup to reply.
  2. Try sort function
    like this

    sort($terms_html)
    foreach($terms_html as $item){
       echo $item;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search