Overriding the currently selected menu item

I have a WP 3.x site that I’m using mainly as a CMS. The menu links to the various WordPress pages.

One of the pages, “News”, is the “posts” page.

Read More

However, when clicking on one of the posts on the News page, the “News” item in the menu loses highlighting because the post isn’t treated as a child of “news”.

Is there an easy way to override the currently highlighted item in the menu? Ideally by forcing a page ID upon it.

Related posts

Leave a Reply

1 comment

  1. Since I assume you’re using wp_nav_menu(), there should be a class current_page_parent which is applied to your posts’ page menu item when viewing a single post.

    You can use this class to style the ‘active’ state, much like you’re probably doing with current_page_item at the moment.

    If (for whatever reason) you must have current_page_item added too, you can filter the nav_menu_css_class:

    /**
     * Add the class 'current_page_item' to 'page for posts' menu item if we're
     * viewing a single post.
     * 
     * @param array $class
     * @param object $item The current menu item.
     * @return array
     */
    function add_current_class_to_posts_page( $classes, $item )
    {
        static $posts_page;
    
        if ( ! is_single() )
            return $classes;
    
        if ( ! isset( $posts_page ) )
            $posts_page = get_option( 'page_for_posts' ); // cache as we may be calling this a lot!
    
        if ( $item->object == 'page' && $item->object_id == $posts_page )
            $classes[] = 'current_page_item'; // this is the posts page!
    
        return $classes;
    }
    add_filter( 'nav_menu_css_class', 'add_current_class_to_posts_page', 10, 2 );