0

我是 Wordpress 的新手。我的版本是 WP 3.4.2 该网站在我的本地主机上,抱歉我不能分享它。

如何根据当前帖子动态突出显示导航菜单项?这个问题在 Stack Overflow 上出现了很多,但我还没有找到任何可接受的答案。我在这里看到的一些答案使用 Javascript,但我不能,因为 20% 的访问者没有 js。

我找到了一个解决方案,使用过滤器挂钩(对我来说是一个新概念)。我在 header.php 中添加了下面的 filter_hook。

这个钩子在正确的帖子上触发,但最终结果是错误的。我的整个菜单不是在我的菜单中添加一个类名“current-menu-item”,而是字符串:“current-menu-item”;

谁能帮我理解我做错了什么?

if(($post->post_type) =="communities")
    add_filter('wp_nav_menu' , 'special_nav_class' , 10 , 2);

function special_nav_class( $item){

     if(true){
             $class = "current-menu-item";
     }
     return $class;
}
4

2 回答 2

6

如果您使用 WordPress嵌入式菜单功能(并且您绝对应该),WordPress 会自动将current-menu-item类添加到当前项,如果当前项在下拉菜单中,则添加current-menu-parent到 main 。LI

然后您所要做的就是将您的 CSS 规则应用于这些类。

于 2013-01-07T18:18:03.663 回答
1

我喜欢首先查看相关过滤器的源代码,例如WordPress Trac上 nav-menu-template.php 的第 237 行的“wp_nav_menu” 。

查看代码,我看到过滤器可以更改 $nav_menu 变量。所以你从这个过滤器返回的任何东西都会变成 html。如果您想更改 CSS 类,您可能需要使用“nav_menu_css_class”过滤器。此过滤器使您能够查看分配的类并以任何方式覆盖它们,即仅使用您指定的类,或添加您的类。

if ( $post->post_type == "communities" ) {
    add_filter( 'nav_menu_css_class', 'special_nav_class', 10 , 3 );
}

function special_nav_class( $classes, $item, $args ){
    if ( true ) {
        $classes[] = "current-menu-item";
    }
    return $classes;
}

我认为您可能想要更多地玩弄这个,以便将您的 if 语句移动到 special_nav_class 函数中。我认为 post_type 可以从您从过滤器收到的 $item 变量中确定。但我不是 100% 的。

于 2013-01-07T18:12:40.053 回答