phpwordpresscategoriesshortcode

How to display a list of subcategories in order by name and not in chronological order?


The category page displays the subcategories under it using the following code:

add_shortcode( 'list_subcats', function() {
ob_start();
$current_cat = get_queried_object();
$term_id = $current_cat->term_id;
$taxonomy_name = 'category';
$term_children = get_term_children( $term_id, $taxonomy_name );
echo '<ul class="list-subcats">';
foreach ( $term_children as $child ) {
$term = get_term_by( 'id', $child, $taxonomy_name );
echo '<li><a href="' . get_term_link( $child, $taxonomy_name ) . '">' . $term->name . '</a></li>';
}
echo '</ul>';
return ob_get_clean();
} );

I would like to display the list of subcategories in alphabetical order by name and not in chronological order


Solution

  • Sort the $term_children or output to an array to sort first. This should give you the desired result.