开发者

Highlighting top level link when viewing one of it's sub-pages

开发者 https://www.devze.com 2023-03-24 13:02 出处:网络
I have a page that is not linked in my custom menu. This page has a parent page, which 开发者_开发百科is linked in the custom menu.

I have a page that is not linked in my custom menu. This page has a parent page, which 开发者_开发百科is linked in the custom menu.

If I go to the "not-linked" page, I want to to highlight it's parent page link in the menu.

Is there a way to do what I want?


You should use wp_get_nav_menu_items to change class of your parent page item. Example:

function my_menu_items_hook($items, $menu, $args) {

  if ( 'my-menu-slug' == $menu->slug ) {
    if ( '/my-child/' == $_SERVER['REQUEST_URI'] ) { // check if current page is child page
      foreach ( $items as $key => $value ) {
        if ( YOUR_PARENT_PAGE_ID == $value->ID ) {
          $items[$key]->classes[] = 'current-menu-item';
        }
      }
    }
  }

  return $items;
}

add_action('wp_get_nav_menu_items', 'my_menu_items_hook', 10, 3);

If your child page could have parameters, then you better use regular expresion or substr function instead checking $_SERVER['REQUEST_URI'] value.

0

精彩评论

暂无评论...
验证码 换一张
取 消