Wordpress — confused, trying to use add_filter to customise wp_list_categories
I currently have a site with a hard-coded list of categories & subcategories, where each item is formatted as follows:
<li class="cat-item open-access"><a href="/categories/open-access/">Open Access</a></li>
Importantly, each <li>
item is assigned a class which matches the slug of the category linked to within.
I would obviously like to use Wordpress' wp_list_categories()
to output the list instead of hard-coding it, but need to keep the custom class for each <li>
item.
I have been looking into filters and actions and thought I might have come up with a fix by adding this to my theme's functions.php
file:
function add_class_from_slug($wp_list_categories) {
$pattern = '/class=\"/';
$replacement = 'class="'.$category->slug.' ';
$newclass = preg_replace($pattern, $replacement, $wp_list_categories);
开发者_C百科 return $newclass;
}
add_filter('wp_list_categories','add_class_from_slug');
But this doesn't work — the text returned by $category->slug
drops out when the page is rendered. If I add in static text (using a line like $replacement = 'class="myclass ';
, it renders fine.
Frustratingly, I can get the output I want by adding $class .= ' '.$category->slug;
at the right spot wp-includes/classes.php
, but want to avoid resorting to that.
Why can't I just use $category->slug
in my function? Workarounds, suggestions, further reading on the subject? Should add that I have a pretty basic grip on PHP. Thanks!
You can extend the Walker_Category
class with your own class and override the function start_el()
.
If the name of the class you used is Walker_MyCategory
, you could call wp_list_categories()
like:
wp_list_categories('walker=Walker_MyCategory')
You could also build your own list yourself. See get_categories()
Oh and your code didn't work because $category wasn't defined anywhere. You need to know exactly what category it is.
精彩评论