Skip to content

Instantly share code, notes, and snippets.

@peterwegren
Last active November 16, 2016 17:21
Show Gist options
  • Save peterwegren/4c25d332bffaedadcba006e3784a3fba to your computer and use it in GitHub Desktop.
Save peterwegren/4c25d332bffaedadcba006e3784a3fba to your computer and use it in GitHub Desktop.
Menu item active class.
<?php
/*
* Menu item active class.
*/
function add_current_nav_class($classes, $item) {
// get current post details
global $post;
// get post type of current post
$current_post_type = !empty($post) ? get_post_type_object($post->post_type) : null;
$current_post_type_slug = $current_post_type && isset($current_post_type->rewrite['slug']) ? $current_post_type->rewrite['slug'] : ( $current_post_type && $current_post_type->name == 'post' ? 'news' : null);
// get URL of the menu item
$menu_slug = strtolower(trim($item->url));
// if menu item URL contains current post types slug add current-menu-item class
if ( $current_post_type_slug ) {
if ( strpos($menu_slug, $current_post_type_slug) !== false ) {
$classes[] = 'current-menu-item';
}
}
// return corrected set of classes to add to menu item
return $classes;
}
add_action('nav_menu_css_class', 'add_current_nav_class', 10, 2 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment