The nav_menu_css_class
filter will let you add CSS classes to specific menu items. We combine that with the get_page_template_slug
function to fetch the page template filename, then we use that with the get_page_templates
method of the theme class to get the template name as defined in the Template Name:
header. Then we pass that result through sanitize_html_class
to make it a valid class name. Lastly, we add it to the array of classes and return it.
function wpd_page_template_nav_class( $classes, $item ) {
// only check pages
if( 'page' == $item->object ){
// if this page has a template assigned
if( $slug = get_page_template_slug( $item->object_id ) ){
// get the array of filenames => template names in the current theme
$templates = wp_get_theme()->get_page_templates();
// if there is a template with key matching our filename
if( isset( $templates[$slug] ) ){
// sanitize it and add it to the classes
$classes[] = sanitize_html_class( $templates[$slug] );
}
}
}
return $classes;
}
add_filter( 'nav_menu_css_class', 'wpd_page_template_nav_class', 10, 2 );