Question

I have given the following arguments in the wp_list_categories function.

<?php wp_list_categories('show_option_all=All&hide_empty=0&title_li=&current_category=All'); ?>

I want the 'All' option to be visible in any category listing. However, since by default, all posts load, the styling for current_category should also apply to 'All'. However, since All does not have a category ID, I do not know how to apply the current-cat class to 'All'.

Any suggestions?

Was it helpful?

Solution

You could fetch the list into a variable (add echo=0 to the parameters), and insert a custom class using string replace.

Update:

Something like this:

<?php 
function str_replace_once($needle , $replace , $haystack){
    $pos = strpos($haystack, $needle);
    if ($pos === false) {
        return $haystack;
    }
    return substr_replace($haystack, $replace, $pos, strlen($needle));
}
    $args = array( 'show_option_all' => 'All',
                    'hide_empty' => '0',
                    'title_li' => '',
                    'current_category' => 'All',
                    'echo' => '0');
            $str = wp_list_categories($args);

            $str = str_replace_once('<li>', '<li class="current-cat">', $str);
            echo $str;
?>

OTHER TIPS

You can use preg_replace to remove some of the complexity. The last parameter limits the number of occurrences to replace.

$list = wp_list_categories([
   'show_option_all' => 'All',
   'hide_empty' => false,
   'title_li' => '',
   'current_category' => 'All',
   'echo' => false
]);

$list = preg_replace('/<li>/', '<li class="current-cat">', $list, 1);
echo $list;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top