ThemesGrove’s resource that suggests using usort() is perfectly acceptable and will do the job. It’s often more efficient though to let SQL order the results as desired instead of using PHP to sort after the query is run. In the case of post tags I doubt one way or the other will make any noticeable difference, so altering the SQL query to order as desired is mainly of academic interest in this case.
the_tags() function relies upon the WP_Term_Query class to get post tags from the DB. We can alter the SQL query that is run to get post tags with the “terms_clauses” filter. In the passed array of SQL clauses, we can alter the ORDER BY clause to sort naturally instead of alphabetically. By default the_tags() already sorts alphabetically by tag name. To cause the name field to be treated numerically, we can mathematically add zero to the name field value to cause it to be cast as an integer value.
add_filter('terms_clauses', 'bcw_order_numeric', 10, 3 );
function bcw_order_numeric( $clauses, $taxonomy, $args ) {
$clauses['orderby'] = 'ORDER BY t.name+0, t.name';
return $clauses;
}
This code, added to the theme’s functions.php, will cause all uses of WP_Term_Query to be natural sorted by name. If you need to limit this only to the particular call to the_tags(), don’t add the filter in functions.php, instead add the filter just before starting the loop that uses the_tags(), then remove the filter after the loop completes.
The t.
as the table reference is an alias established in the query’s FROM clause for the terms table. We add t.name
after t.name+0
so that tag names with no numbers will be still be sorted alphabetically.