Menü schliessen
Created: August 26th 2013
Categories: Wordpress
Author: Marcus Fleuti

Wordpress :: Highlight menu item when a single custom post or a post from a category is shown

Donation Section: Background
Monero Badge: QR-Code
Monero Badge: Logo Icon Donate with Monero Badge: Logo Text
82uymVXLkvVbB4c4JpTd1tYm1yj1cKPKR2wqmw3XF8YXKTmY7JrTriP4pVwp2EJYBnCFdXhLq4zfFA6ic7VAWCFX5wfQbCC

What's that?

WordPress does NOT automatically assign a menu highlight class on custom single-posts when you insert the custom menu with wp_nav_menu(). For this we wrote the following simple function as a hook within functions.php.

The solution

Add the following code to your functions.php and be happy:

/* function to add classes to active menu entries */
function add_active_class_to_custom_posts($classes = array(), $menu_item = false){
    global $wp_query;
    $post_name = $menu_item->post_name;
    $post_type = get_post_type();

    /* Highlight the current menu item if the category-parent of the current posts' category equals to the menu name.
     * This is usually the case when you set a category as custom menu item and use wp_nav_menu() to display that */
    $query_var = get_query_var('cat');
    if ($query_var) {
        $current_category = get_category($query_var);
        $root_categoryObj = get_category($current_category->parent, false);
        $root_categoryName = strtolower(($root_categoryObj->name));
        if (strcasecmp($post_name, $root_categoryName) == 0) $classes[] = 'current-menu-item';    
    }
    
    /* assign 'current-menu-item' to regular posts; that's the default behaviour we just copy here */
    if(in_array('current-menu-item', $menu_item->classes)){
        $classes[] = 'current-menu-item';
    }
    else {
        /* assign the 'current-menu-item' class to all custom posts */
        if ($post_name == $post_type) {
            $classes[] = 'current-menu-item';
        }
    }
    return $classes;
}
add_filter( 'nav_menu_css_class', 'add_active_class_to_custom_posts', 10, 2 );