X

Add ancestor class to single posts

Ok so, when you open a single post page (i.e. single.php), you don’t get any current_page_item nor current-page-ancestor classes on your wp_nav_menu, right? And you can’t tell the user in which section they currently are.
Well, this function checks if the name in the labels array of your custom-post-type or category (if it’s a standard post) matches the page title and, if that’s the case, it adds the current-page-ancestor class to your nav menu.
Just copy and paste the snippet in your functions.php file and you’re done.

P.S. Obviously, if the generic name in the labels doesn’t exactly match the title of the page, it won’t add the class, so double-check that.

Code Snippet:

<?php
function add_single_post_ancestor_nav_class($classes, $item){
    global $post;
    $is_ancestor = false;
    if ( is_single() ) {
        if ( $post->post_type != 'post' ) {
        	// Checks if the custom-post-type label name matches the title of the nav-page-item
        	$post_type_obj = get_post_type_object($post->post_type);
        	$post_type_labels = $post_type_obj->labels;
        	$post_type_name = $post_type_labels->name;
        	if( $item->title == $post_type_name ) { $is_ancestor = true; }
        }
        else {
        	// Checks if one of the single-post categories matches the title of the nav-page-item
        	$categories = get_categories();
        	foreach ( $categories as $category ) {
        		if ( in_category($category->name) && $item->title == $category->name ) { $is_ancestor = true; }
        	}
        }
        if( $is_ancestor ){ $classes[] = 'current-page-ancestor'; }
    }
    return $classes;
}
add_filter('nav_menu_css_class' , 'add_single_post_ancestor_nav_class' , 10 , 2);
?>

Comments  Leave a Reply

Add a Comment

We're glad you have chosen to leave a comment. Please keep in mind that all comments are moderated according to our privacy policy, and all links are nofollow. Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.

WordPress Launch Checklist

The Ultimate WordPress Launch Checklist

We've compiled all the essential checklist items for your next WordPress website launch into one handy ebook.
Yes, Send Me the Free eBook!