-2

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

  • 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. – Nicolai Nov 17 '13 at 15:24
  • Why is this not possible with pure CSS? – s_ha_dum Nov 17 '13 at 15:44
2

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;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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