php - 当页面不是该菜单项的子项时,如何将活动类添加到 Wordpress 菜单项?
问题描述
在 Wordpress 中,我设置了一个名为“single-event.php”的文件,我用它来呈现来自名为“事件”的自定义帖子类型的每个帖子的完整数据。
我还有一个“活动”页面,其中包含一些预告信息和每个帖子的固定链接。
但是,由于单个事件页面(使用 single-event.php 模板)不是事件页面的子页面,因此它们不会将 .current-page-ancestor 类添加到事件菜单项中。
我看到了使用主体类和导航项 ID 突出显示“事件”菜单项的建议,但是,客户端可能会重新排序或重命名页面,然后这种方法可能会中断。
任何更好的建议都非常感谢。
谢谢,史蒂夫
解决方案
我建议尝试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;
}
推荐阅读
- c# - 尝试在 Visual Studio for Mac 中的 C# 中读取 JPEG 图像时出现 System.PlatformNotSupportedException
- perl - 如何将分叉子程序的哈希内容传递回主程序?
- javascript - 如何在 axios 中创建一个全局变量?
- python - 无法在 python 中打印与 CSV 文件(时间轴)具有相同日期的折线图
- python - 如何编辑直方图上的 x 轴标签?在 matplotlib 上
- ios - 如何为 Native Base Datepicker 添加确认和取消按钮
- python - 如何使用 Digi XBee Python 模块向远程 XBee 发送 API 帧?
- excel - 将日期添加到选项卡
- .htaccess - .htaccess 限制对根级页面的访问。我该如何阻止这个?
- python - python - 如何将字典与一个键合并到python中的另一个键字典?