WordPress Snippet: Output tag cloud of all tags in all posts also tagged with a particular tag

How is that for a title?

In my previous post I mentioned my quest to build a better tag.php. My personal desire was to have the tag.php page display a tag cloud of all the tags in all the posts that were also tagged the same tag.

The following WordPress/PHP code does exactly that.

NOTE: I have two level deep subqueries here and I am sure there is a better way to write the SQL but I am too tired and lazy to fix it right now. But I wanted to post this in the meantime anyway in case anyone else needed something similar and to expose folks to the $wpdb object.

/**
 * Output tag cloud for all tags of all posts with the current tag
*/

// Get the current tag "term_taxonomy_id" so we can get all the related term_ids
$current_term_taxonomy_id = $wp_query->queried_object->term_taxonomy_id;
// Query for a comma separated list of term_ids for all posts with the current associated tag
$result = $wpdb->get_results("
        SELECT      GROUP_CONCAT(term_id) as concat_term_id
        FROM        $wpdb->term_taxonomy
        WHERE       term_taxonomy_id IN (
                        SELECT      term_taxonomy_id
                        FROM        $wpdb->term_relationships
                        WHERE       object_id IN (
                            SELECT      object_id
                            FROM        $wpdb->term_relationships
                            WHERE       term_taxonomy_id = $current_term_taxonomy_id
                        )
                    );
    ", OBJECT );

// Save that list of related term_ids
$related_term_ids = $result[0]->concat_term_id;

// Set the parameters for our tag cloud (mostly defaults here)
$args = array(
        'number'                    => 0, //45
        'include'                   => $related_term_ids,
        'echo'                      => false
    );
// And finally get the formatted tag cloud
$related_tag_cloud = wp_tag_cloud( $args );
// So you can output it however you like...
echo "<p><strong>More tags found in posts also tagged \"{$this_taxonomy_title}\"</strong><br />{$related_tag_cloud}</p>";

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>