How to add a CSS Class to ul
and anchor element of Tag Cloud generated through wp_tag_cloud
function?
I want the default class for ul
of wp-tag-cloud
to be tag-cloud
and anchor tag would have btn btn-xs btn-primary
class.
<ul class="tag-cloud">
<li><a class="btn btn-xs btn-primary" href="#">Apple</a></li>
<li><a class="btn btn-xs btn-primary" href="#">Barcelona</a></li>
<li><a class="btn btn-xs btn-primary" href="#">Ipod</a></li>
</ul>
3 s
We can also modify the anchor CSS class with the wp_generate_tag_cloud_data
filter (4.3+).
With that filter we can modify the following anchor data:
id
url
role
name
title
(removed in 4.8)slug
real_count
class
font_size
formatted_count
(added in 4.8)aria_label
(added in 4.8)show_count
(added in 4.8)
The style attribute is hardcoded, as can be seen from the 4.8 version:
$a[] = sprintf(
'<a href="https://wordpress.stackexchange.com/questions/225693/%1$s"%2$s class="%3$s" style="font-size: %4$s;"%5$s>%6$s%7$s</a>',
esc_url( $tag_data['url'] ),
$tag_data['role'],
esc_attr( $class ),
esc_attr( str_replace( ',', '.', $tag_data['font_size'] ) . $args['unit'] ),
$tag_data['aria_label'],
esc_html( $tag_data['name'] ),
$tag_data['show_count']
);
Note that we can change the font-size unit with:
wp_tag_cloud( [ 'unit' => 'rem', 'smallest' => 1, 'largest' => 4 ] );
or e.g. with the widget_tag_cloud_args
filter for the tag cloud widgets.
Example:
Here we append the btn btn-xs btn-primary
classes to anchors in all tag clouds:
add_filter( 'wp_generate_tag_cloud_data', function( $tag_data )
{
return array_map (
function ( $item )
{
$item['class'] .= ' btn btn-xs btn-primary';
return $item;
},
(array) $tag_data
);
} );