提问者:小点点

当页面不是Wordpress菜单项的子菜单项时,如何向该菜单项添加活动类?


在Wordpress中,我设置了一个名为“单一事件”的文件。我正在使用php从一个名为“Events”的自定义post类型呈现每个post的完整数据。

我还有一个“事件”页面,它为每篇文章拉一些预告信息和永久链接。

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

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

如有更好的建议,我们将不胜感激。

谢谢,史蒂夫


共1个答案

匿名用户

我reccomend尝试nav_menu_css_class过滤器添加活动类当前菜单项current_page_item菜单项基于当前加载的模板。

apply_过滤器('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;
}