Steve Gibbons
Steve Gibbons

Reputation: 71

How to add an active class to a Wordpress menu item when the page is not a child of that menu item?

In Wordpress, I have set up a file named 'single-event.php' which I am using to render the full data for each post from a Custom Post Type called "Events".

I also have an 'events' page, which pulls some teaser info and a permalink for each post.

However, as the single event pages (using the single-event.php template) are not children of the events page they do not get a .current-page-ancestor class added to the events menu item.

I have seen a suggestion to use the body class and nav item ID to highlight the 'events' menu item, however, the client may reorder or rename pages, and this approach may then break.

Any better suggestions greatly appreciated.

Thanks, Steve

Upvotes: 1

Views: 1312

Answers (1)

Jasper B
Jasper B

Reputation: 881

I reccomend trying nav_menu_css_class filter to add the "active" classes current-menu-item and current_page_item to the menu item based on the current loaded template.

apply_filters( 'nav_menu_css_class', string[] $classes, WP_Post $item, stdClass $args, int $depth )

something like this

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

function my_menu_class_filter($classes, $item){
  global $post;
  if($item->ID !== 123){return $classes;} //Replace the ID with the id of your events teaser page
  if($post->post_type === 'event'){
    $classes[] = 'current-menu-item';
    $classes[] = 'current_page_item';
  }
  return $classes;
}

edit: Variation for the child page

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

function my_menu_class_filter($classes, $item){
  global $post;
  if($item->ID !== 123){return $classes;} //Replace the ID with the id of your events teaser page
  if($post->post_type === 'event'){
    $classes[] = 'current-page-ancestor';
    $classes[] = 'current-menu-ancestor';
    $classes[] = 'current-menu-parent';
    $classes[] = 'current-page-parent';
    $classes[] = 'current_page_parent';
    $classes[] = 'current_page_ancestor';
  }
  return $classes;
}

Upvotes: 1

Related Questions