Do you want to add ancestor class to single posts? When you open a single post page (i.e. single.php), you don’t get any current_page_item or current-page-ancestor classes on your wp_nav_menu. You can’t also tell your users in which section they currently are.
Instructions:
All you have to do is add this code to your theme’s functions.php file or in a site-specific plugin:
<?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);
?>
If the generic name in the labels don’t match the title of the page, then it won’t add the class.
Note: If this is your first time adding code snippets in WordPress, then please refer to our guide on how to properly copy / paste code snippets in WordPress, so you don’t accidentally break your site.
If you liked this code snippet, please consider checking out our other articles on the site like: 7 best VPN services for WordPress users and 12 best WordPress podcast plugins.
Can you put the code on this page? I can’t see it…
Updated!