Skip to content

Snippets / PHP

PHP HTML CSS

Taxonomy Cloud

D Donald McGuinn · 214 views · Updated 2 years ago
Create a tag cloud of taxonomies similar to the built in wordpress one, but works better.
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 · 49 lines
Change the post_tag to the slug of your taxonomy.
[custom_wordcloud taxonomy="post_tag"]
HTML · 1 lines
.custom-wordcloud span a {
text-decoration: none;
color: #333;
}

.custom-wordcloud span a:hover {
color: #0073aa;
}
CSS · 8 lines

Discussion 1

Ask a question or share how you used this.

Log in to join the discussion.
Moshy 2 years ago

hi will i be bale to let the user in the frontend when he creates a post be able to add tags by himself, or only what the admin has added?

Donald McGuinn 2 years ago

No you cannot. And voxel will not be adding that functionality.

Moshy 2 years ago

thank you for your response do you know why not?

Donald McGuinn 2 years ago

the team feels like it would cause chaos for sure.

Moshy 2 years ago

i understand, but for me i think its very necessary, do you know if there is a plugin i could try that would give me that functionality?

Voxel Guide assistant
Ask about snippets, addons & how-tos

Hey — how can I help?

I can dig through the library for snippets, addons, and tutorials.

AI can be wrong — double-check anything important.