2

I would like to show most used tags first in single post page, archieve page and on homepage.

For example:

I have 4 tags- Ball(5 posts), Doll(3 posts), Cat(2 posts), Apple(1 post). Whenever I put more than one tags in a post, these tags shows in the alphabetical order but I want to show the most used tags first.

2

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 );  
}
  • 1
    There's also the wp_list_sort() core utility function. – birgire Apr 13 '18 at 15:45
  • Added the wrapper implementation as an alternative. – birgire Apr 15 '18 at 8:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.