Sort results alphabetically in custom foreach loop
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 itreturn '<ul>' . implode( $terms_html ) . '</ul>';
Try sort
function
like this
sort($terms_html)foreach($terms_html as $item){ echo $item;}