I have categories and subcategories.
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();
} );
The subcategories are listed in chronological order.
I would like to display the list of subcategories in order by name and not in chronological order.
Is it possible to display the subcategories list by name and not in chronological order with this code?
2
Answers
Can you sort the $term_children?
or output to an array to sort first ?
This should give you the desired result.
To display the list of subcategories ordered by name instead of chronological order, you can modify the code as follows:
Replace this line:
with:
This uses the
get_terms()
function to retrieve the subcategories based on the$term_id
and$taxonomy_name
. Theorderby
parameter is set to'name'
to sort the subcategories by name, and theorder
parameter is set to'ASC'
for ascending order.Update the
foreach
loop to use the$child
object directly instead of fetching the term again:Since
$term_children
now contains the term objects, you can directly access theterm_id
andname
properties of each$child
object.Here’s the updated code:
With these changes, the subcategories will be displayed in alphabetical order by name.