Skip to content

Snippet: Add the current-menu-item class to the Main Page for Singular Post Types

By default active classes aren't added to the portfolio, staff, testimonials items in the main menu while viewing the singular posts, however, it's very easy to add via the snippet below. This will check if the current menu item is the parent post type page as defined in the post type settings in your WP admin and if so and it's a singular post type page than it will receive the active menu item class.

/**
 * Add current-menu-item class to the main page when viewing portfolio, staff, testimonial posts.
 *
 * @link https://totalwptheme.com/docs/snippets/current-menu-post-type-parent-pages/
 */
add_filter( 'nav_menu_css_class', function( $classes = [], $menu_item = false ) {
	$types = [ 'portfolio', 'staff', 'testimonials' ];
	foreach ( $types as $type ) {
		if ( is_singular( $type ) && $menu_item->object_id == get_theme_mod( $type . '_page' ) ) {
			$classes[] = 'current-menu-item';
		}
	}
	return $classes;
}, 10, 2 );

/**
 * Add current-menu-item class to Post Type Unlimited singular posts.
 */
add_filter( 'nav_menu_css_class', function( $classes = [], $menu_item = false ) {
	if ( ! is_callable( 'PTU\PostTypes::get_registered_items' ) ) {
		return $classes;
	}
	$ptu_posts = PTU\PostTypes::get_registered_items();
	foreach ( $ptu_posts as $ptu_post_id ) {
		$ptu_post_name = get_post_meta( $ptu_post_id,  '_ptu_name', true );
		if ( is_singular( $ptu_post_name ) && $menu_item->object_id == get_post_meta( $ptu_post_id,  '_ptu_total_main_page', true ) ) {
			$classes[] = 'current-menu-item';
		}
	}
	return $classes;
}, 10, 2 );
All PHP snippets should be added via child theme's functions.php file or via a plugin. We recommend Code Snippets (100% Free) or WPCode (sponsored)
Back To Top