Retrieve the most used post tags and display them in a ordered list

Views: 22 Last modified: August 20th, 2011 Comments: 0

This function for wordpress will return a HTML ordered list (numbered), containing the top X most used post tags. This function accepts 2 parameters. The first one will be the amount of tags, and the second one could be set to false (boolean) when you don’t want to show the amount of posts where the tag has been tagged on. The second parameter is by default true (show the amount), which makes the parameter optional.

<?php
/**
 * GetTopXTags()
 * Returns ordered HTML list with the top X tags
 * @param int $top_x
 * @param bool $count
 * @return string $str
 */
function GetTopXTags($top_x, $count = true){
if (!is_int($top_x))
    return false;

    global $wpdb;
    $str = '';

    $count = ($count) ? ', taxonomy.count' : '';

        $tags = $wpdb->get_results(
                    $wpdb->prepare("SELECT terms.name, terms.slug {$count}
                                        FROM $wpdb->terms AS terms
                                            INNER JOIN $wpdb->term_taxonomy AS taxonomy
                                            ON terms.term_id = taxonomy.term_id
                                                WHERE taxonomy.taxonomy = 'post_tag'
                                                AND taxonomy.count > 0
                                                    ORDER BY taxonomy.count DESC
                                                        LIMIT %d ", $top_x), OBJECT);
    $str = '<ol>';
        foreach ($tags as $tag){
            $term_obj = get_term_by('slug', $tag->slug, 'post_tag', OBJECT);
                $show_count = ($count) ? '('.$tag->count.')' : '';
                $str .= '<li class="top-tags"><a href="'.get_tag_link($term_obj->term_id).'" class="top-tags-list">'.strtolower($tag->name).' '.$show_count.'</a></li>';
        }
    $str .= '</ol>';

        return $str;
}

// echo the list, without count
echo GetTopXTags(5, false);

// echo the list, with count
echo GetTopXTags(5);
?>
Attachments 1 image(s) & 0 video(s) found.
VN:F [1.9.13_1145]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.13_1145]
Rating: 0 (from 0 votes)

    Mail this!

    To: From:Sum {7+9} =  
    Anything to add ?

        You must be logged in to post a comment.