How to add active class on current menu item page?

I have two links: Products and News.

When i click on Products or News, it returns me an archive page that contains some posts, when i click on a post it returns me a single page of this post.

Read More

In the menu I use this code on <li> to add a class called active if the page is home:

<li<?php if(is_home()) {?> class="active"<?php } ?>>

But i dont know how to do it when I have two archive pages and two singles pages.

If i use if( is_archive() || is_single() ) it’ll add class on both menu itens.

Some help would be appreciated.

Related posts

2 comments

  1. You could add conditional classes for each in your child theme functions file:

    Here’s one example you can modify to suit your own needs.

    add_filter('nav_menu_css_class' , 'wpsites_nav_class' , 10 , 2);
    
    function wpsites_nav_class($classes, $item){
    
    if( is_archive() && $item->title == "Products"){     
    
             $classes[] = "products-class";
     }
     return $classes;
    

    Source http://codex.wordpress.org/Function_Reference/wp_nav_menu#Adding_Conditional_Classes_to_Menu_Items

    You can then style your nav menu using the new class in your child themes style.css file.

    .products-class {
    
    Your CSS declarations
    }
    

    This CSS code is conditional based on the PHP code above.

  2. I suppose your Products and News posts are custom posts.
    For both conditional tags, there is a $post_type-specific equivalent:

    if (is_post_type_archive('products')) {
       // ...
    } elseif (is_post_type_archive(array('news', 'something'))) {
       // ...
    } elseif (is_singular('products')) {
       // ...
    } elseif (is_singular(array('news', 'something'))) {
       // ...
    }
    

    So, for Products, it would be:

    if (is_post_type_archive('products') || is_singular('products'))
    

    News accordingly.

    References:

Comments are closed.