In this article I will explain you how you can customize the tag cloud of your WordPress site by using a filter. First I will show a code example, then I will explain the technical details and where you can find the filter documentation.
A typical tag cloud customization is the font size, because by default WordPress uses 8pt for the smallest tag. Google search console can report this text as too small to read on mobile devices. It may also report that clickable tags in the tag cloud are too close together. If this happens, you should fix these problems to have a good usability of your site.
I found the solution by digging into the WordPress code . The solution is using the filter widget_tag_cloud_args. For example, if you want to set the font size of the smallest tag to 12px, the code you have to use is:
add_filter('widget_tag_cloud_args', 'my_filter_custom_tag_cloud');
function my_filter_custom_tag_cloud( $cloud_args ){
$cloud_args['smallest'] = 12;
$cloud_args['unit'] = 'px';
return $cloud_args;
}
Here you are changing both the font size to 12 and the unit to px. The default values are 8 for the font size and pt for the unit. According to the comments in the WordPress code, the unit key “accepts any valid CSS text size unit”.
You can also customize the font size of the largest tag by using $cloud_args[‘largest’]. The default value is 22pt.
To customize the separator between the tags you will use $cloud_args[‘separator’]. The default separator is \n.
For example to set the smallest tag to 12px, the largest to 24px and to add extra space between the tags you can use this code:
add_filter('widget_tag_cloud_args', 'my_filter_custom_tag_cloud');
function my_filter_custom_tag_cloud( $cloud_args ){
$cloud_args['smallest'] = 12;
$cloud_args['largest'] = 24;
$cloud_args['unit'] = 'px';
$cloud_args['separator'] = " \n ";
return $cloud_args;
}
Technical explanation of how to customize WordPress tag cloud
Let’s see the technical details. As of WordPress version 5.2.x the tag cloud widget code is contained in the file wp-includes/widgets/class-wp-widget-tag-cloud.php. The filter widget_tag_cloud_args is defined in the method WP_Widget_Tag_Cloud::widget. WordPress filters are created by calling the function apply_filters.
Actually it is the function wp_generate_tag_cloud() in the file wp-includes/category-template.php the one that generates the tag cloud. The DocBlock (documentation above the function name) of this function explains the parameters of the filter widget_tag_cloud_args. You can find the filter reference documentation here.