2

Is there any way to display template name (or page-template.php filename) in each menu items' class? Maybe using wp_nav_menu walker?

Specifically, I'm using standard menu call:

wp_nav_menu( array( 'menu' => 3, 'container' => false )

Which gives me:

<div class="menu-wrap">
<ul id="menu-menu" class="menu">
<li id="menu-item-979" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-979"><a href="#">Homepage</a></li>
<li id="menu-item-844" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-844"><a href="#">Subpage</a></li>
</ul>
</div>

And if I have template names Homepage and Subpage, I'd like to get the same, but with template name classes:

<div class="menu-wrap">
<ul id="menu-menu" class="menu">
<li id="menu-item-979" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-979 Homepage"><a href="#">Homepage</a></li>
<li id="menu-item-844" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-844 Subpage"><a href="#">Subpage</a></li>
</ul>
</div>

Thanks!

1 Answer 1

2

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 );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.