views:

17

answers:

1

Hi all,

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);
        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!

+1  A: 

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.

Zahymaka
Thanks. This is what I've now done and it works perfectly. Overriding `start_el()` by extending `Walker_Category` in my theme's `functions.php` file allows complete control over the way my categories are listed.If anyone comes across this post wanting to do something similar, I found these two posts to be pretty useful in understanding what Wordpress's `Walker` class is, and how to modify/extend it:http://scribu.net/wordpress/extending-the-category-walker.htmlhttp://wordpress.org/support/topic/how-can-i-get-wp_list_pages-separated-by-commas
poisontofu
Glad to hear it worked for you.
Zahymaka