Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I need to have a class of current-menu-item added to a li with the id of #menu-item-127 if the body class is post-type-archive-team

I can do this with jQuery -

$(function(){
    if ($('body').hasClass('post-type-archive-team')) {
        $('#menu-item-127').addClass('current-menu-item');
    }
});

But it's needed before jQuery loads to make something else work.

Any ideas if I can do this with PHP?

Thanks in advance

share|improve this question
1  
It'd be better not just to ask how to solve a problem, because that seems like a »do my work for me« question. Which isn't appreciated, see on topic at help center and How to Ask. Best would be you present your research effort and if possible some code you've tried. –  ialocin Nov 17 '13 at 15:24
    
Why is this not possible with pure CSS? –  s_ha_dum Nov 17 '13 at 15:44

1 Answer 1

Use the nav_menu_css_class() filter. The following function will add the current-menu-item class to a page identified by it's slug. You can

Update the $cpt_name and $menu_item_id variables to reflect your setup.

add_filter( 'nav_menu_css_class', 'nav_parent_class', 10, 2 );

function nav_parent_class( $classes, $item ) {
    $cpt_name = 'team';
    $menu_item_id = 127; // id of menu item to add current-menu-item class to

    if ( $cpt_name == get_post_type() && is_archive() && ! is_admin() ) {
        // remove any active classes from nav (blog is usually gets the currept_page_parent class on cpt single pages/posts)
        $classes = array_filter($classes, ($class == 'current_page_item' || $class == 'current_page_parent' || $class == 'current_page_ancestor'  || $class == 'current-menu-item' ? false : true ));

        // check if slug matches menu item id
        if( $item->ID == $menu_item_id ) {
            $classes[] = 'current-menu-item';
        }
    }

    return $classes;
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.