Highlighting the 'All' category in wp_list_categories
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=¤t_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?
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;
?>
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;
精彩评论