Last active
August 29, 2015 14:13
-
-
Save gpspake/d3037a6bc1018bf01eb3 to your computer and use it in GitHub Desktop.
Conditionally highlight WordPress menu items
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//This is useful if you want to highlight menu items conditionally. | |
//Example highlight the 'Blog' menu item when you are on a single post | |
//Highlight a custom link menu item when you are on a custom post type | |
//http://www.tammyhartdesigns.com/wordpress/highlight-menu-item-for-custom-post-types/ | |
add_filter('nav_menu_css_class', 'thd_menu_classes', 10, 2); | |
function thd_menu_classes($classes, $item) | |
{ | |
$post_types = array( | |
'news_notes' => '/in-the-media', | |
'announcement' => '/announcements' | |
); | |
if (get_post_type() == 'news_notes' || is_archive('news_notes')) { | |
// find the url you want and add the class you want | |
if ($item->url == '/in-the-media') { | |
$classes = str_replace('menu-item', 'menu-item active', $classes); | |
remove_filter('nav_menu_css_class', 'thd_menu_classes', 10, 2); | |
} | |
} elseif (get_post_type() == 'announcement') { | |
// find the url you want and add the class you want | |
if ($item->url == '/announcements') { | |
$classes = str_replace('menu-item', 'menu-item active', $classes); | |
remove_filter('nav_menu_css_class', 'thd_menu_classes', 10, 2); | |
} | |
} | |
return $classes; | |
} | |
/* | |
* Highlight parent-page menu items on child-pages | |
*/ | |
add_filter('nav_menu_css_class', 'thd_menu_classes', 10, 2); | |
function thd_menu_classes($classes, $item) | |
{ | |
global $post; | |
if ($post->post_parent) { | |
$post_data = get_post($post->post_parent); | |
$parent_name = $post_data->post_name; | |
if(strpos($item->url,$parent_name)) { | |
$classes = str_replace('menu-item', 'menu-item active', $classes); | |
remove_filter('nav_menu_css_class', 'thd_menu_classes', 10, 2); | |
} | |
} | |
return $classes; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment