To ensure the "Journal" menu item is highlighted for single posts without adding individual posts as sub-items in the menu, you can use a WordPress filter and some custom CSS or JavaScript. Here's a solution that involves adding a bit of PHP to your theme's functions.php file to modify the menu classes.
Step 1: Add a Filter in functions.php
Add the following code to your theme's functions.php file. This code checks if the current page is a single post and then adds the current-menu-item class to the "Journal" menu item:
function highlight_journal_menu_item($classes, $item) {
// Check if we're on a single post
if (is_singular('post')) {
// Get the ID of the "Journal" page
$journal_page_id = get_option('page_for_posts');
// If the current menu item matches the "Journal" page ID, add the 'current-menu-item' class
if ($item->object_id == $journal_page_id) {
$classes[] = 'current-menu-item';
}
}
return $classes;
}
add_filter('nav_menu_css_class', 'highlight_journal_menu_item', 10, 2);
Step 2: Ensure Menu Items Have Proper Classes
WordPress typically adds classes like current-menu-item to the active menu item, which is why this filter works by adding that class to the "Journal" menu item when viewing a single post.
Explanation:
is_singular('post'):
Checks if the current page is a single blog post.
get_option('page_for_posts'): Retrieves the ID of the page assigned to display posts, in this case, your "Journal" page.
$item->object_id == $journal_page_id: Compares the current menu item's ID with the "Journal" page ID and adds the current-menu-item class if they match.
Summary
This approach automatically highlights the "Journal" menu item whenever a single post is viewed without the need to add individual posts as sub-items. The PHP filter works dynamically and is a clean solution to keep your menu structure intact.