The category_css_class WordPress PHP filter allows you to modify the CSS classes applied to each category in the list.
Usage
add_filter('category_css_class', 'your_custom_function_name', 10, 4); function your_custom_function_name($css_classes, $category, $depth, $args) { // your custom code here return $css_classes; }
Parameters
- $css_classes (string[]): An array of CSS classes to be applied to each list item.
- $category (WP_Term): Category data object.
- $depth (int): Depth of page, used for padding.
- $args (array): An array of
wp_list_categories()
arguments.
More information
See WordPress Developer Resources: category_css_class
Examples
Adding a custom CSS class to all categories
Add a custom CSS class ‘custom-class’ to all categories in the list.
add_filter('category_css_class', 'add_custom_class_to_categories', 10, 4); function add_custom_class_to_categories($css_classes, $category, $depth, $args) { $css_classes[] = 'custom-class'; return $css_classes; }
Adding a CSS class based on category ID
Add a unique CSS class to each category based on its ID.
add_filter('category_css_class', 'add_id_based_class_to_categories', 10, 4); function add_id_based_class_to_categories($css_classes, $category, $depth, $args) { $css_classes[] = 'category-id-' . $category->term_id; return $css_classes; }
Removing all default CSS classes
Remove all default CSS classes from the categories in the list.
add_filter('category_css_class', 'remove_default_css_classes', 10, 4); function remove_default_css_classes($css_classes, $category, $depth, $args) { return array(); }
Adding a CSS class based on category depth
Add a CSS class to categories based on their depth in the hierarchy.
add_filter('category_css_class', 'add_depth_based_class_to_categories', 10, 4); function add_depth_based_class_to_categories($css_classes, $category, $depth, $args) { $css_classes[] = 'category-depth-' . $depth; return $css_classes; }
Modifying CSS classes conditionally
Add a custom CSS class to categories with a specific parent category.
add_filter('category_css_class', 'add_class_to_specific_parent_categories', 10, 4); function add_class_to_specific_parent_categories($css_classes, $category, $depth, $args) { if ($category->parent == 123) { // Replace 123 with the desired parent category ID $css_classes[] = 'custom-class-for-parent'; } return $css_classes; }