WordPress wp_list_categories, how to highlight the “All categories”

I have use wp_list_categories to create category list and setting $args as below for add class “current-cat” to the current category item, everything work fine but when I click “All categories” I can’t highlight the list menu because the class “current-cat” don’t apply to “All categories” item.

How to apply the current-cat class to “All categories” ?

Read More

My setting

<ul>
    <?php 
        $args = array(
        'show_option_all'    => 'All Categories',
        'orderby'            => 'id',
        'style'              => 'list',
        'use_desc_for_title' => 0,
        'hierarchical'       => 0,
        'title_li'           => '',
        'current_category'   => 0
        );
        wp_list_categories( $args ); 
    ?>  
</ul>

HTML output

<ul>
  <li class="cat-item-all"><a href="http://example.com/">All Categories</a></li>
  <li class="cat-item cat-item-1 current-cat"><a href="http://example.com/category/category-one/">Category one</a></li>
  <li class="cat-item cat-item-2"><a href="http://example.com/category/category-two/">Category two</a></li>
  <li class="cat-item cat-item-3"><a href="http://example.com/category/category-three/">Category three</a></li>
  <li class="cat-item cat-item-4"><a href="http://example.com/category/category-four/">Category four</a></li>
</ul>

Related posts

Leave a Reply

1 comment

  1. If you don’t echo the results and instead store them in a variable we can check if that class exists. And if it doesn’t then that means we are on the ‘All’ category.

    So to achieve this I did the following:

    $args = array(
        'show_option_all' => 'All',
        'title_li' => '',
        'echo' => false, // dont echo the results
        'taxonomy' => 'tribe_events_cat'
    );
    
    $categories = wp_list_categories($args); // store the results in a variable
    
    if(strpos($categories,'current-cat') == false) { // check if the class exists
        // add the class to the All item if it doesn't exist
        $categories = str_replace('cat-item-all', 'cat-item-all current-cat', $categories);
    }
    
    echo $categories;
    

    You will have to change the $args to suit your purpose.