Getting Recent Tags for WordPress Posts

Here’s something I wanted for my Delicious clone Savory — a list of the most recent tags added to posts. This question was answered on Stack Overflow. I copied that code and made a couple handy functions to insert directly into any theme or plugin. I should probably add a UNIQUE clause in there somewhere to filter out duplicate tags 🙂

 * get recent tags
function get_recent_tags($limit = 10) {
  global $wpdb;    
  $sql = "SELECT $wpdb->terms.term_id, $wpdb->, $wpdb->terms.slug
          FROM $wpdb->terms   
          INNER JOIN $wpdb->term_taxonomy ON ($wpdb->terms.term_id = $wpdb->term_taxonomy.term_id)
          INNER JOIN $wpdb->term_relationships ON ($wpdb->terms.term_id = $wpdb->term_relationships.term_taxonomy_id)
          INNER JOIN $wpdb->posts ON ($wpdb->term_relationships.object_id = $wpdb->posts.ID)
          WHERE $wpdb->term_taxonomy.taxonomy = 'post_tag'
          ORDER BY $wpdb->posts.post_date DESC LIMIT 1,$limit";    
  return $wpdb->get_results($wpdb->prepare($sql));

 * echo recent tags
function the_recent_tags($before = "<ul class='recenttags'><li>", $between = "</li><li>", $after = "</li></ul>") { 
  // before  
  echo $before;
  // each tag
  $tags = $this->get_recent_tags();    
  $tag_html = function($x) {
    return sprintf("<a href=\"" . get_tag_link( $x->term_id) . "\">%s</a>", $x->name);
  $tag_a = array_map($tag_html, $tags );
  echo implode($between, $tag_a);    
  // after
  echo $after;    

Leave a Reply