Taxonomy Cloud

Description/Instructions

Create a tag cloud of taxonomies similar to the built in wordpress one, but works better.

If this snippet helped, feel free to buy me a taco :)

function custom_taxonomy_wordcloud_shortcode($atts) {
// Set default attributes and merge with user inputs
$atts = shortcode_atts(
array(
'taxonomy' => 'category', // Default taxonomy
),
$atts,
'custom_wordcloud'
);

// Get terms from the specified taxonomy
$terms = get_terms(array(
'taxonomy' => $atts['taxonomy'],
'hide_empty' => true,
));

if (empty($terms) || is_wp_error($terms)) {
return 'No terms found.';
}

// Set up the word cloud
$word_cloud = '<div style="font-size:1rem;">';
$max_font_size = 20;
$min_font_size = 12;

// Calculate max and min post counts
$post_counts = array_map(function($term) {
return $term->count;
}, $terms);
$max_posts = max($post_counts);
$min_posts = min($post_counts);

// Generate the word cloud HTML
foreach ($terms as $term) {
$font_size = $min_font_size + ($max_font_size - $min_font_size) * (($term->count - $min_posts) / ($max_posts - $min_posts));
$word_cloud .= sprintf('<span style="font-size:%spx; margin-right:10px;"><a href="%s">%s</a></span>',
$font_size,
get_term_link($term),
esc_html($term->name)
);
}

$word_cloud .= '</div>';

return $word_cloud;
}

// Register the shortcode with WordPress
add_shortcode('custom_wordcloud', 'custom_taxonomy_wordcloud_shortcode');

  • PHP
Copy Code

Instructions

Change the post_tag to the slug of your taxonomy.

[custom_wordcloud taxonomy="post_tag"]

  • HTML
Copy Code

.custom-wordcloud span a {
text-decoration: none;
color: #333;
}

.custom-wordcloud span a:hover {
color: #0073aa;
}

  • CSS
Copy Code

Let's Chat About this Snippet