The the_category WordPress PHP filter modifies the category or list of categories for a given post.
Usage
add_filter('the_category', 'your_custom_function', 10, 3); function your_custom_function($thelist, $separator, $parents) { // your custom code here return $thelist; }
Parameters
$thelist
(string) – List of categories for the current post.$separator
(string) – Separator used between the categories.$parents
(string) – How to display the category parents. Accepts ‘multiple’, ‘single’, or empty.
Returns
More information
See WordPress Developer Resources: the_category
Examples
Change the separator between categories
Change the default separator to a comma and space.
function change_category_separator($thelist, $separator, $parents) { $separator = ', '; return implode($separator, array_filter(array_map('trim', explode($separator, $thelist)))); } add_filter('the_category', 'change_category_separator', 10, 3);
Add an icon before each category
Add a custom icon before each category.
function add_icon_before_category($thelist, $separator, $parents) { return str_replace('<a', '<i class="your-icon-class"></i><a', $thelist); } add_filter('the_category', 'add_icon_before_category', 10, 3);
Remove specific category from the list
Remove a specific category from the category list by its ID.
function remove_specific_category($thelist, $separator, $parents) { $category_to_remove = 5; // Replace with your category ID return preg_replace('/<a href="[^>]*?category-' . $category_to_remove . '[^>]*>(.*?)<\/a>/', '', $thelist); } add_filter('the_category', 'remove_specific_category', 10, 3);
Change category link target to “_blank”
Open category links in a new tab.
function open_categories_in_new_tab($thelist, $separator, $parents) { return str_replace('<a', '<a target="_blank"', $thelist); } add_filter('the_category', 'open_categories_in_new_tab', 10, 3);
Display only the first category
Show only the first category in the category list.
function show_first_category_only($thelist, $separator, $parents) { $categories = array_filter(array_map('trim', explode($separator, $thelist))); return reset($categories); } add_filter('the_category', 'show_first_category_only', 10, 3);