Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save Garconis/ba0fdaa2be314546c17c2cd8598822c3 to your computer and use it in GitHub Desktop.
Save Garconis/ba0fdaa2be314546c17c2cd8598822c3 to your computer and use it in GitHub Desktop.
WordPress | Tag cloud for categories via shortcode
<?php
function tag_cloud_shortcode($atts) {
// first make sure we are within a category
if (is_category()) {
// get info of current category
$category = get_category( get_query_var( 'cat' ) );
// get current category ID
$cat_id = $category->cat_ID;
// loop through all posts within the current category ID
$query_args = array( 'cat' => $cat_id, 'posts_per_page' => -1 );
// create the new query
$custom_query = new WP_Query( $query_args );
// if this category has posts
if ($custom_query->have_posts()) {
while ($custom_query->have_posts()) : $custom_query->the_post();
// grab the tags of each post in this query
$posttags = get_the_tags();
// if there are any tags that belong to posts in this query
if ($posttags) {
// for each one, grab that tag ID
foreach($posttags as $tag) {
$all_tags[] = $tag->term_id;
}
}
endwhile;
}
// create list of each unique tag ID that as found
$tags_arr = array_unique($all_tags);
// pull the array apart to get each unique tag ID
$tags_str = implode(",", $tags_arr);
// display parameters for the output of the tags
$args = array(
'echo' => false,
'smallest' => 12,
'largest' => 20,
'unit' => 'px',
'number' => 0,
'format' => 'list',
'order' => 'count',
'include' => $tags_str
);
// if the current category did have posts, then output the tag cloud and other information
if ($custom_query->have_posts()) {
return '<div class="fs-tag-wrapper"><h4 class="widgettitle">'. get_cat_name($cat_id) .' Tags</h4><div class="fs-tags">'. wp_tag_cloud($args) .'</div></div>';
}
// otherwise the current category didn't have any posts, so return nothing (otherwise it would try to return ALL tags of ANY category posts)
else {
return '';
}
}
}
add_shortcode( 'tagscloud', 'tag_cloud_shortcode' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment