The category_list_link_attributes WordPress PHP filter allows you to modify the HTML attributes applied to a category list item’s anchor element.
Table of contents
Usage
add_filter('category_list_link_attributes', 'your_custom_function', 10, 4);
function your_custom_function($atts, $category, $depth, $args) {
// your custom code here
return $atts;
}
Parameters
$atts(array) – The HTML attributes applied to the list item’s<a>element. Empty strings are ignored.href(string) – The href attribute.title(string) – The title attribute.
$category(WP_Term) – Term data object.$depth(int) – Depth of the category, used for padding.$args(array) – An array of arguments.$current_object_id(int) – ID of the current category.
More information
See WordPress Developer Resources: category_list_link_attributes
Examples
Add a custom class to category links
This example adds a custom class ‘custom-category-link’ to all category list item anchor elements.
add_filter('category_list_link_attributes', 'add_custom_class_to_category_links', 10, 4);
function add_custom_class_to_category_links($atts, $category, $depth, $args) {
$atts['class'] = 'custom-category-link';
return $atts;
}
Add a data attribute to category links
This example adds a ‘data-category-id’ attribute to all category list item anchor elements.
add_filter('category_list_link_attributes', 'add_data_attribute_to_category_links', 10, 4);
function add_data_attribute_to_category_links($atts, $category, $depth, $args) {
$atts['data-category-id'] = $category->term_id;
return $atts;
}
Modify the title attribute of category links
This example adds the phrase ‘Click to view’ before the category name in the title attribute.
add_filter('category_list_link_attributes', 'modify_title_attribute_of_category_links', 10, 4);
function modify_title_attribute_of_category_links($atts, $category, $depth, $args) {
$atts['title'] = 'Click to view ' . $category->name;
return $atts;
}
Change href attribute to use a custom URL structure
This example changes the href attribute to use a custom URL structure for category links.
add_filter('category_list_link_attributes', 'change_href_attribute_of_category_links', 10, 4);
function change_href_attribute_of_category_links($atts, $category, $depth, $args) {
$atts['href'] = '/custom-url-structure/' . $category->slug;
return $atts;
}
Add an inline style for padding based on category depth
This example adds inline CSS padding to the left of category links based on their depth.
add_filter('category_list_link_attributes', 'add_padding_based_on_depth', 10, 4);
function add_padding_based_on_depth($atts, $category, $depth, $args) {
$padding = 10 * $depth;
$atts['style'] = "padding-left: {$padding}px;";
return $atts;
}