This is possible by first getting the raw tag data with get_the_tags()
sorting the results by the count
property of each tag with usort()
, then looping through them and outputting them as links:
/*
* Get array of tags and sort by count.
*/
$tags = get_the_tags();
if ( $tags && ! is_wp_error( $tags ) ) {
usort( $tags, function( $a, $b ) {
return $b->count - $a->count; // Swap $a and $b for ascending order.
} );
/*
* Get an HTML link for each tag and put in an array.
*/
$links = array();
foreach ( $tags as $tag ) {
$links[] = '<a href="' . esc_url( get_tag_link( $tag ) ) . '" rel="tag">' . $tag->name . '</a>';
}
/*
* Output links separated by comma.
*/
echo implode( ', ', $links );
}
Another implementation is to create a wrapper of the_tags()
, that reorders the tags with wp_list_sort()
via the get_the_terms
filter:
/**
* Retrieve the tags for a post, ordered by post count.
*
* @param string $before Optional. Before list.
* @param string $sep Optional. Separate items using this.
* @param string $after Optional. After list.
*/
function the_tags_wpse( $before = null, $sep = ', ', $after="" ) {
add_filter( 'get_the_terms', $callback = function( $tags ) {
return wp_list_sort( $tags, 'count', 'desc' );
}, 999 );
the_tags( $before, $sep, $after );
remove_filter( 'get_the_terms', $callback, 999 );
}