Remove Parentheses from Category Post Count

When you use "wp_list_categories" function to display the list of categories with post count, the parentheses shows up by default. However, if you are using this function within your custom theme, there are ways to remove the parentheses. It can be done fairly easily using following method.

<?php
// get the categories
$cat = wp_list_categories(array(
   'echo' => 1,
   'show_count' => 1,
   'title_li' => '<h3>Categories</h3>'));
   // replacing parentheses
   $clean = str_replace(array('(',')'), '', $cat);
   echo $clean;
?>

All we are doing here is simply replacing the parentheses from the returned value and only then echoing them. Now, you might wonder what about if you are using widgets to display list of categories with their post count?! In such scenario, we can use the following method to replaces the parentheses.

<?php
function filter_post_count_parentheses($cat) {
   // replacing parentheses
   $cat = str_replace(array('(',')'), '', $cat);
   return $cat; }
add_filter('wp_list_categories','filter_post_count_parentheses');
?>

In this case, we are using "add_filter" to hook "wp_list_categories" with the function to remove the parentheses. Notice that I am using the same "str_replace" (string replace) function.

You can get creative here on this specific function. Let's say, you want to not only replace the parentheses but also want to wrap the post count with a "div" or "span" element. You can do it like this.

<?php
function replace_post_count_parentheses($cat) {
   $cat = str_replace('(', '<span>', $cat);
   $cat = str_replace(')', '</span>', $cat);
   return $cat; }
add_filter('wp_list_categories','replace_post_count_parentheses'); 
?>

In this case we are replacing both the parentheses with the opening and closing (<span></span>) tag. You can assign class to this tag and can style them anyway you want. Hope this helps.

References: wp_list_categories, str_replace, add_filter.

Related

Comments

Comments list