Wordpress菜单突出显示

I am new to Wordpress. My version is WP 3.4.2 The site is on my localhost, sorry I cannot share it.

How do I dynamically highlight a nav menu item based on current post? This question appears here on Stack Overflow quite a bit, but I have not found any accepted answers. Some answers I have seen here use Javascript but I cannot because 20% Of my visitors don't have js.

I found a solution, using filter hooks ( a new concept to me ). I have added the filter_hook below, in header.php.

This hook fires on the correct posts, but the final result is wrong. Instead of adding a class name "current-menu-item" to 1 item in my menu, My whole menu is just the string:"current-menu-item";

Can anyone please help me understand what I have done wrong?

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;
}

If you use WordPress embedded menu functionality (and you definitely should) WordPress automatically adds current-menu-item class to the current item, and current-menu-parent to the main LI, if the current item is in a drop-down menu.

Then all you have to do is apply your CSS rules to these classes.

I like to to start by looking at the source code for the filter in question, in the case of 'wp_nav_menu' that is line 237 of nav-menu-template.php on WordPress Trac.

Reviewing the code I see that the filter enables the $nav_menu variable to be altered. So whatever you return from this filter will literally become the html. If you want to alter the CSS class you may want to use the 'nav_menu_css_class' filter instead. This filter enables you to review the assigned classes and override them in anyway, be that to only use a class you specify, or to add your 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;
}

I think you may want to toy with this some more though to move your if statement into the special_nav_class function. I think the post_type can be determined from the $item variable you receive from the filter. But I'm not 100% on that.