【问题标题】:How to add an active class to a Wordpress menu item when the page is not a child of that menu item?当页面不是该菜单项的子项时,如何将活动类添加到 Wordpress 菜单项?
【发布时间】:2021-08-14 15:20:41
【问题描述】:

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

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

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

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

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

谢谢, 史蒂夫

【问题讨论】:

    标签: php wordpress


    【解决方案1】:

    我建议尝试nav_menu_css_class 过滤器,根据当前加载的模板将“活动”类current-menu-itemcurrent_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;
    }
    

    【讨论】:

    • 您好贾斯珀,感谢您的回复。我找到了我的事件预告页面的页面 ID(它是 17),并且我将您的代码放入了我的函数文件中,但是,菜单类没有任何变化。目前我已经实现了 CSS 方法,但当我有更多时间时会重新审视这个,感谢您的回复。史蒂夫
    • 嗨史蒂夫,请仔细检查if($post->post_type === 'event') 语句中的帖子类型是否正确,您可以在创建新事件时在您的 URL 中找到此内容/wp-admin/post-new.php?post_type=product 此示例适用于帖子类型的 woocommerce 产品将是product,你必须将代码放在你的主题function.php中
    猜你喜欢
    • 2018-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-24
    • 1970-01-01
    相关资源
    最近更新 更多