Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

WordPress

Guido Grulke
Guido Grulke
20,948 Points

add dynamically a css class to menu-item

Hi,

I want to make sure that I choose the right way or want to learn if there is a better or easier way to achieve my goal.

I want to style the menu item 'contact' with a different bg-color on each static page (based on the page template). So the menu is the same for all (static) pages, only the background-color of the 'contact' item should change.

e.g. on the front-page the 'contact' menu-item should have a bg-color: green; on page-one the 'contact' menu-item should have a bg-color: blue; a.s.o.

I added the following function into my templates header.php:

**
* Create an additional css class to the custom menu item, so that we can style the menu item based on the page-template
*
* @package theme_name
* @since 1.0
*/

add_filter('nav_menu_css_class', 'special_nav_class', 10 , 2);

function special_nav_class( $classes, $item ) {

// we need to know on which page we are
global $wp_query; 
$template_name = get_post_meta( $wp_query->post->ID, '_wp_page_template', true ); //get the filename of the template
$template_name = str_replace(".php", "", $template_name);   //cut the .php

if( $item->title == 'contact' ){ //we want to add a separate class to the contact menu item, depending on the page

     $classes[] = "header-".$template_name; //here we go - add header-pagename to the css class of contact
} 
return $classes;
}

So it works fine for me. Please let me know your ideas or any improvement I could add.

Thanks.

2 Answers

Guido Grulke
Guido Grulke
20,948 Points

thanks for your attention.

yes, the _wp_page_template is a standard wp feature. I found this in the wp-support forum and the entry is from Justin Tadlock, so I trust.

Huh, I guess I'll have to go review all the predefined meta fields because I'm sure there's stuff in there I've been writing custom code to address. Nice find.

I think you're actually doing it right, this seems like a perfect time to reach for a filter.

However, I think I might have noticed a WP feature I've never known about, is _wp_page_template a predefined meta field that gives you the filename of the template?