If you’ve ever added a custom link to a WordPress menu item that directs to a custom post type archive, you’ve probably been dismayed at the fact that the highlighting classes such as “current_page_item” aren’t added for you and even worse, “current_page_parent” is added to the menu item for the page that displays your recent blog posts. Here’s a quick snippet that will help you get the desired class structure:
add_filter( 'nav_menu_css_class', 'namespace_menu_classes', 10, 2 );
function namespace_menu_classes( $classes , $item ){
if ( get_post_type() == 'event' || is_archive( 'event' ) ) {
// remove that unwanted classes if it's found
$classes = str_replace( 'current_page_parent', '', $classes );
// find the url you want and add the class you want
if ( $item->url == '/events' ) {
$classes = str_replace( 'menu-item', 'menu-item current_page_item', $classes );
remove_filter( 'nav_menu_css_class', 'namespace_menu_classes', 10, 2 );
}
}
return $classes;
}
I usually added a custom class to the menu item, and used it in conjunction with the body class:
.event-archive .events
That’s one solution, but doing something like this allows you to not rely on settings within WordPress since it’s controlled by the theme or plugin this code is in.
Hi Tammy, great stuff! I’m learning a lot from your tuturials. I’ve included this code in my plugin but $item->url returns as string consisting of all the url’s of the menu pasted together, so the ‘current_page_item’ class is not added.
Sorry for the noob question, teaching myself as I go along.
best,
Demu