0

很多人,无论是在 SOW 还是在其他地方,都遇到了我同样的问题。

我已经在我的网站上安装了 BBpress 插件。这个插件在网站上启用了一个论坛。

I've wrestled for days (to no avail) on this documented issue where the plugin causes the wrong menu item to be highlighted when any Forum sub-menu item is chosen. 相反,默认情况下,博客菜单项会突出显示。

检查一下:点击论坛,这个结果页面会突出显示“论坛”菜单项。但是点击“测试论坛”(或深入到任何其他论坛项目),结果页面总是突出显示“博客”。

到目前为止,这是我所知道的:

  • 它不能单独使用 CSS 修复。
  • 我正在使用永久链接(选择了“帖子名称”)
  • PHP 根据您导航到的页面为菜单项分配一个.current-menu-item和/或一个.current_page_item类(以及它们对应的-ancestor和类)。-parent由于某种原因,它无法将任何论坛子菜单视为当前页面。因此,它默认将“博客”作为当前页面项。
  • 所以我知道我需要执行以下操作:
    1. 让 Wordpress 在每个页面加载时检查 URL
    2. 如果"/forums/"是 URL 的一部分,则删除所有.current-menu*.current_page*(通配符是清除祖先/父类所必需的)
    3. 然后为菜单项分配.current-menu-item.current_page_item分类。"Forum"

问题是,虽然我认为我已经接近了,但我不知道如何 - 确切地 - 做到这一点。

我已经尝试了很多东西。

我找到了这个Jquery 解决方案,但不知道如何实现它,我对这种方法也没有信心:

// First add a “forum-class” to your forums menu item in your custom menu 
// Then add this to your js file with YOURURL = the url of your site and forums = your forums slug : 

$(function() { 
    var forumURL = window.location.href.indexOf("YOURURL/forums/");
    if(forumURL > -1){
        $('li.forum-class').addClass('current-menu-item');
    }   
});

然后,我发现这种方法似乎更接近我想要的,但它引入了一个新类,并且似乎没有从博客菜单中清除不正确的类。另外,我不知道究竟该把这段代码放在哪里,或者在哪里创建 js 文件。

if (strtolower($thats_all->post_title) == "forum" || strtolower($thats_all->post_title) == "forums") {
    $addclass = ' class="current_page"';
} else {
    $addclass = '';
}

最后,我发现我认为我需要的,但我在实现它时遇到了麻烦(我试过把它粘在我的身上menu-primary.phpheader.php但没有成功)。

// this forces the class current-menu-item to a menu item which I named 'forums' 

add_filter('nav_menu_css_class', 'remove_link_parent_menu_classes', 420 ,3);
function remove_link_parent_menu_classes($classes, $item, $args){

if(strpos($item->url, '/forums/') !== true)
    return array_diff($classes, array('current_page_item', 'current-menu-item'));

return $classes;
}

我想我很接近了。真的很近。只需要朝着正确的方向推动。我需要知道:

  • 上面的后一种解决方案会起作用吗?
  • 哪个文件,以及文件中的确切位置,我需要放置代码吗?

谢谢!

4

1 回答 1

0

我终于破解了!使用上述线索,我找到了对我有用的代码。

add_filter( 'nav_menu_css_class', 'namespace_menu_classes', 10, 2 );
function namespace_menu_classes( $classes , $item ){
    if ( get_post_type() == 'forum' ) {
        $classes = str_replace( 'current_page_parent', '', $classes );
        $classes = str_replace( 'menu-item-16', 'current_page_parent', $classes );
    }
    return $classes;
}

将上述内容复制到function.php文件末尾。

然后更改'forum'为您选择的 slug 名称并替换'menu-item-16'为您想要突出显示的正确编号的菜单项(您需要使用 Web 浏览器的开发人员工具来检查您的站点才能找到它)。

这花了我一周的时间来弄清楚(并学习所需的 php)!祝你好运,希望这可以帮助其他所有人。

于 2014-08-22T04:11:02.820 回答