Quantcast
Channel: My CMS
Viewing all articles
Browse latest Browse all 19

How to add class on current menu

$
0
0

So the new WordPress menus introduced in 3.0 are great but the Menus panel of the WordPress Dashboard limits us in what we can add to our menus. If, for example, we want to add archive pages for custom post types we end up having to add them as “Custom Links”. This is an easy work-around, but doing this robs us of the ability to highlight the current menu item when a user is viewing this page.

Here is a simple hack that you can add to your themes functions.php file, or build into your plug-in in order to identify when a “Custom Link” page is active, and add the “current-menu-item” class.

add_filter('nav_menu_css_class', 'AddCurrentMenuItemClass',1,2);
 
function AddCurrentMenuItemClass($classes,$item)
{
$link = site_url().$_SERVER['REQUEST_URI'];
if(strpos($link, $item->url) !== false)
{
$classes[] = 'current-menu-item';
}
return $classes;
}

If you don’t want the menu item to get the current-menu-item class when viewing a sub-page, use the following:

add_filter('nav_menu_css_class', 'AddCurrentMenuItemClass',1,2);
 
function AddCurrentMenuItemClass($classes,$item)
{
$link = site_url().$_SERVER['REQUEST_URI'];
if(strcmp($link, $item->url) == 0)
{
$classes[] = 'current-menu-item';
}
return $classes;
}

Make sure the url for the Custom Link matches the format of the $link variable. That is to say, it should be the full site_url (you can find out this value by looking at Settings > General in the WordPress Dashboard) followed by your archive page slug.

The post How to add class on current menu appeared first on My CMS.


Viewing all articles
Browse latest Browse all 19

Trending Articles