Search code examples
wordpresstags

Get all tags based on specific category (including all tags from child categories and posts) wordpress


I wanted to use wp_tag_cloud() on single.php using the argument that gets all tags from specific category including all tags from its child categories and posts.


Solution

  • I am getting closer on this.

    <div class="tag_cloud_on_single">
    
        <h2>Popular Topics</h2>
    
        <?php
    
        $category = get_the_category();
        $root_cat_of_curr =  $category[0]->category_parent;
    
        function get_cat_slug($cat_id) {
            $cat_id = (int) $cat_id;
            $category = &get_category($cat_id);
            return $category->slug;
        }
    
        $my_cat = get_cat_slug($root_cat_of_curr);
    
        $custom_query = new WP_Query('posts_per_page=-1&category_name='.$my_cat.'');
        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);
    
        $args = array(
            'smallest'                  => 12, 
            'largest'                   => 24,
            'unit'                      => 'pt', 
            'number'                    => 0,  
            'format'                    => 'flat',
            'separator'                 => "&nbsp;&nbsp;&nbsp;",
            'orderby'                   => 'name', 
            'order'                     => 'RAND',
            'exclude'                   => null,  
            'topic_count_text_callback' => default_topic_count_text,
            'link'                      => 'view', 
            'echo'                      => true,
            'include'                   => $tags_str
        );
    
        wp_tag_cloud($args);
    
        ?>
    
    </div>
    

    Thanks all for your contribution. Appreciate your help.