Child category is set current-cat on parent page

I have parent categories which have childs. I’m listing child categories on parent category page.

I’m using archive.php template.

Read More

Now I’m facing issue with current-cat class on parent category page.
Seems that my first child category is getting current-cat class when on parent category page. This current-cat class should be on only when on current category page.

For example my parent category is Fruits. And when I’m on Fruits (category/fruits) page I can see child categories Apple, Orange, Banana. Problem is that Apple is getting current-cat class on Fruits page.

It should get that class only when on Apple page (category/fruits/apple).

Here is my current code:

global $wp_query;

$ID = $wp_query->posts[0]->ID; 
$postcat = get_the_category($ID);
$cat = $postcat[0]->cat_ID; 
$thiscat = get_category ($cat); 
$parent = $thiscat->category_parent; 

if ($parent == 0) {

}

else { 

    $subcategories = get_categories('child_of='.$parent);
    $items='';
        foreach($subcategories as $subcat) {
            if($thiscat->term_id == $subcat->term_id) 
              $current = ' current-cat'; 
            else $current = ''; 
              $items .= '
            <li class="cat-item cat-item-'.$subcat->term_id.$current.'"> 
                <a href="'.get_category_link( $subcat->term_id ).'" title="'.$subcat->description.'">'.$subcat->name.' </a>
            </li>';
    }
    echo "<ul>$items</ul>";
    }

?>

How to fix my code?

Related posts

1 comment

  1. When you are on the archive template, this code:

    global $wp_query;
    
    $ID = $wp_query->posts[0]->ID; 
    $postcat = get_the_category($ID);
    $cat = $postcat[0]->cat_ID; 
    $thiscat = get_category ($cat); 
    

    Is loading the category from the first post. That first post could be in one, two, or multiple categories, so getting the category ID this way is not reliable.

    Instead, there are some other ways – try this method – to get the category ID for which the archive is intended to be loading:

    $cat = get_query_var('cat');
    $thiscat = get_category($cat);
    $parent = ($thiscat->category_parent) ? $thiscat->category_parent : $thiscat->term_id;
    

Comments are closed.