Borgtex
Borgtex

Reputation: 3245

make a wordpress tag cloud of an specific category link to a list of articles of that category & tag

I need to show a tag cloud of all the tags of a particular category, so I'm using a function to retrieve all the tags:

function tags_by_cat($cat_id)
{
$custom_query = new WP_Query("posts_per_page=-1&cat={$cat_id}");
if ($custom_query->have_posts()) :
    while ($custom_query->have_posts()) : $custom_query->the_post();
        $posttags = get_the_tags();
        if ($posttags) {
            foreach($posttags as $tag) {
                $all_tags[] = $tag->term_id;
            }
        }
    endwhile;
endif;

$tags_arr = array_unique($all_tags);
$tags_str = implode(",", $tags_arr);

return $tags_str;
}

and then I generate the tag cloud in the template, for example for category 33:

wp_tag_cloud( array('smallest'=>8,'largest'=>22,'include'=>tags_by_cat(33)));

the problem is that while it works fine, every tag of this cloud links to a list of all articles containing the tag, but I need to have this list filtered by the original category. Wordpress already can do this (i.e. http://www.website.com/?cat=33&tag=computing) but I can't find how to introduce a url parameter in the urls of the cloud. I'm also using post name permalinks, so that probably makes things more complicated.

Is there some parameter to do what I want or maybe I can I do it with some kind of hook? I was going to recreate my own wp_tag_cloud but I'm not very sure of where to begin

Upvotes: 2

Views: 1615

Answers (1)

Borgtex
Borgtex

Reputation: 3245

Well I've finally created a hook that seems to work properly, for those who may have the same problem:

add_filter ( 'wp_tag_cloud', 'tag_cloud_add_cat' );
function tag_cloud_add_cat( $taglinks ) {
    if (is_category())
    {
        $category = get_category( get_query_var( 'cat' ) );
        $current_cat_slug = $category->slug;

        $tags = explode('</a>', $taglinks);     
        $regex = "#(.*href=\')(.*)(' class.*)#e";       
            foreach( $tags as $tag ) {          
            $varin=strpos($tag,"?")!==false?'&':'?';
            $tagres[] = preg_replace($regex, "'$1$2{$varin}category_name={$current_cat_slug}$3'", $tag );
            }
        $taglinks = implode('</a>', $tagres);
    }
    return $taglinks;
}

Upvotes: 1

Related Questions