This ain't pretty, maybe a MySQL junkie can optimize it a little;
SELECT $wpdb->terms.term_id, $wpdb->terms.name, $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
This basically joins the term, term taxonomy, term relationship and post tables together, getting terms that are of the taxonomy 'post_tag', and currently have a relation with a post, then ordering them by the post's date, descending.
You might get the same term in the result set multiple times, but I can't work out how to use GROUP BY
or HAVING
to fix this, without messing up the date order.
So an example might in use might be;
$tags= $wpdb->get_results($query); // $query being the above SQL
foreach ($tags as $tag) {
if (!isset($stack[$tag->term_id]))
$stack[$tag->term_id] = $tag;
}
print_r($stack); // should print an array of all tags, ordered by last used