There was a quesiton in the WordPress IRC channel just a little while ago asking if there was a way to add a class to the li tag of parent categories generated by the wp_list_categories function.

The first idea that came to mind was using javascript, but a PHP solution will work without the requirement of running javascript on the client machine.

The solution is to read the output of wp_list_comments into a variable, split/explode the string into an array, loop through the array checking if the next element is <ul class='children'>, if the next element is the child ul then add a class to the current li and echo, otherwise just echo the element. Sounds easy right? The code is actually easier to write than describing it using words. As with all of my WordPress code snippets relating to a theme change I have used the WordPress default theme. The following code goes in sidebar.php and replaces the current wp_list_categories function.

<?php
$categories = wp_list_categories('show_count=1&title_li=<h2>Categories</h2>&echo=0');
$category_array = preg_split('/n/', $categories);
$count = count($category_array);
$i = 0;
while ( $i < $count ) {
        if ( preg_match('/<ul class=('|")children('|")/i', $category_array[$i+1]) ) {
                echo preg_replace('/<li class=('|")(.+)('|")>/i', '<li class=$1parent $2$3>', $category_array[$i]) . "n";
        } else {
                echo $category_array[$i] . "n";
        }
        $i++;
}
?>

Enjoy!