The wp_list_categories WordPress PHP filter allows you to modify the HTML output of a taxonomy list.
Usage
add_filter('wp_list_categories', 'your_custom_function', 10, 2); function your_custom_function($output, $args) { // your custom code here return $output; }
Parameters
- $output (string): The HTML output of the taxonomy list.
- $args (array|string): An array or query string of taxonomy-listing arguments. See
wp_list_categories()
for information on accepted arguments.
More information
See WordPress Developer Resources: wp_list_categories
Examples
Adding a custom class to all category links
In this example, we’ll add a custom class named “my-custom-class” to all category links.
add_filter('wp_list_categories', 'add_custom_class_to_category_links', 10, 2); function add_custom_class_to_category_links($output, $args) { $output = str_replace('<a href=', '<a class="my-custom-class" href=', $output); return $output; }
Adding an icon before each category name
This example shows how to add a font-awesome icon before each category name.
add_filter('wp_list_categories', 'add_icon_to_category_names', 10, 2); function add_icon_to_category_names($output, $args) { $output = str_replace('</a>', ' <i class="fas fa-folder"></i></a>', $output); return $output; }
Wrapping category count in a span element
This example demonstrates how to wrap the category count in a span element with a custom class.
add_filter('wp_list_categories', 'wrap_category_count', 10, 2); function wrap_category_count($output, $args) { $output = preg_replace('/(\(\d+\))/', '<span class="category-count">$1</span>', $output); return $output; }
Removing empty categories from the list
In this example, we’ll remove all empty categories from the list.
add_filter('wp_list_categories', 'remove_empty_categories', 10, 2); function remove_empty_categories($output, $args) { $output = preg_replace('/<li class="cat-item.*>\s*<a.*>\s*.*<\/a>\s*\(0\)\s*<\/li>/', '', $output); return $output; }
Changing the default separator between categories
This example shows how to change the default separator between categories from a list to a horizontal line.
add_filter('wp_list_categories', 'change_category_separator', 10, 2); function change_category_separator($output, $args) { $output = str_replace('</li>', '</li><hr>', $output); return $output; }