So I was playing around with this website, and I noticed when viewing the 404, search and some other custom WordPress pages it would highlight my “Blog” menu with a current_page_parent class. How annoying!
I think I’ve found a fix, it works for me but I would love others to test to confirm.
The code which was automatically highlighting the “Blog” menu item is located in nav-menu-template.php and it looks like this:
if ( ! empty( $home_page_id ) && 'post_type' == $menu_item->type && empty( $wp_query->is_page ) && $home_page_id == $menu_item->object_id ) $classes[] = 'current_page_parent';
I didn’t want to modify this core template file, so I found a filter that I could hook into and “reverse” this line of code. Here’s the solution: (add this to your functions.php file)
function dtbaker_wp_nav_menu_objects($sorted_menu_items, $args){ // check if the current page is really a blog post. global $wp_query; if(!empty($wp_query->queried_object_id)){ $current_page = get_post($wp_query->queried_object_id); if($current_page && $current_page->post_type=='post'){ //yes! }else{ $current_page = false; } }else{ $current_page = false; } $home_page_id = (int) get_option( 'page_for_posts' ); foreach($sorted_menu_items as $id => $menu_item){ if ( ! empty( $home_page_id ) && 'post_type' == $menu_item->type && empty( $wp_query->is_page ) && $home_page_id == $menu_item->object_id ){ if(!$current_page){ foreach($sorted_menu_items[$id]->classes as $classid=>$classname){ if($classname=='current_page_parent'){ unset($sorted_menu_items[$id]->classes[$classid]); } } } } } return $sorted_menu_items; } add_filter('wp_nav_menu_objects','dtbaker_wp_nav_menu_objects',10,2);
yes, it’s messy – but it works, if someone wants to post a cleaned up version go for it 🙂
Works for me. Nice. Thank you!
Thanks this was driving me nuts. I modified it slightly to save on a DB call (just removed the get_post bit)
http://pastebin.com/M9Bfx56R