首页 > 解决方案 > 当页面不是该菜单项的子项时,如何将活动类添加到 Wordpress 菜单项?

问题描述

在 Wordpress 中,我设置了一个名为“single-event.php”的文件,我用它来呈现来自名为“事件”的自定义帖子类型的每个帖子的完整数据。

我还有一个“活动”页面,其中包含一些预告信息和每个帖子的固定链接。

但是,由于单个事件页面(使用 single-event.php 模板)不是事件页面的子页面,因此它们不会将 .current-page-ancestor 类添加到事件菜单项中。

我看到了使用主体类和导航项 ID 突出显示“事件”菜单项的建议,但是,客户端可能会重新排序或重命名页面,然后这种方法可能会中断。

任何更好的建议都非常感谢。

谢谢,史蒂夫

标签: phpwordpress

解决方案


我建议尝试nav_menu_css_class过滤以根据当前加载的模板添加“活动”类current-menu-item和菜单项。current_page_item

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

像这样的东西

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

编辑:子页面的变化

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

推荐阅读