I’m using wp_list_categories();
to show a list of all the terms within a custom taxonomy but I need to style list items that have children differently to those that don’t.
Is there a way, PHP or jQuery, that I can give all parent elements a special class?
jQuery solution:
You could try this if you want to use jQuery:
to add the class
i-have-kids
to all theli
parents that include the itemsul.children
, within the HTML generated fromwp_list_categories()
.Category walker solution:
You could take a look at the
Walker_Category
class in/wp-includes/category-template.php
and extend it with an extra part like:If we skip the feed image and feed parts, the extended walker could look like this:
You could further take out the parts that you don’t need.
Usage example:
Output example:
Here’s a list example, using the
Walker_Category_Find_Parents
walker:with the following HTML structure:
I just removed the
title
attributes to make it more readable.But you can see where the
i-have-kids
class is added to theli
tags with children.When I visit the
/ Animals / Birds /
category, the HTML structure becomes:You can hook into the filter that is implemented for this exact purpose as follows. My example will add a “has_children” class to the parent element.