0

I'm trying to display some tags cloud in different locations of my Wordpress. I'm using a shortcode but I'm looking for a way to display only the tags from a specific category ID by adding this ID right in the shortcode like:

 [tagscloud cat_id='2']

I made this but I'm stuck because I don't know how to filter/apply (not sure about the right term) the cat_id.

function wp_tags_cloud_shortcode($atts) {

    extract(shortcode_atts(array(
        'cat_id' => ''
    ), $atts));

    $content = wp_tag_cloud( array( 
    'echo'      => false,
    'smallest'  => 10,
    'largest'   => 10,
    'unit'      => 'px',
    'number'    => 0,
    'format'    => 'flat',
    'orderby'   => 'count' ) 
    );
    return $content;    
}
add_shortcode( 'tagscloud', 'wp_tags_cloud_shortcode' );

I'm a beginner with php so any help will be much appreciate :)

  • you mean tag related to post inside this category ? – Temani Afif Dec 24 '17 at 13:47
  • Yes, exactly. I'm displaying a list of all post from a specific category and I'd like to display a tags cloud in the sidebar of that page. – dragoeco Dec 24 '17 at 14:00
  • In your shortcode, you're using cat, in the function, you're looking for cat_id. Pick one. – janh Dec 24 '17 at 16:58
0

I've finally found a working solution :

function tag_cloud_shortcode($atts) {

    extract(shortcode_atts(array(
        'cat' => ''
    ), $atts));

    $query_args = array( 'cat' => $atts, 'posts_per_page' => -1 );
    $custom_query = new WP_Query( $query_args );
    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(
    'echo'      => false,
    'smallest'  => 10,
    'largest'   => 10,
    'unit'      => 'px',
    'number'    => 0,
    'format'    => 'flat',
    'order'     => 'count',
    'include'   => $tags_str
    );
    return wp_tag_cloud($args);
}
add_shortcode( 'tagscloud', 'tag_cloud_shortcode' );

Now I can use this shortcode with multiple category ID

[tagscloud cat=3,5]

Thanks to Jon Yablonski's post, Nate Beers's answer and code.tutsplus.com

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.