I’m trying to find a way that changes the classes of the different nav menu items, based on the value of a meta key in the page.
The menu currently looks like this:
<li class="menu-item-1">Menu item 1</li>
<li class="menu-item-2">Menu item 2</li>
<li class="menu-item-3">Menu item 3</li>
<li class="menu-item-4">Menu item 4</li>
<li class="menu-item-5">Menu item 5</li>
Using custom keys I want to fetch the individual key from each page and put them in the corresponding menu item, as a class like:
<li class="menu-item-1 pink">Menu item 1</li>
<li class="menu-item-2 yellow">Menu item 2</li>
<li class="menu-item-3 green">Menu item 3</li>
<li class="menu-item-4 pink">Menu item 4</li>
<li class="menu-item-5 bordeaux">Menu item 5</li>
This is what I’ve got so far:
add_filter('nav_menu_css_class' , 'special_nav_class' , 10 , 2);
function special_nav_class($classes, $item){
global $post;
$colorcode = get_post_meta($post->ID, 'color_dropdown', true);
if(is_page()) {
$classes[] = $colorcode;
}
return $classes;
}
What it does is that it adds the meta key to the classes, but only when visiting the page that has a meta key value assigned, and then it adds it to all menu items, which is not right.
I cannot fall back to the menu editor manually using the CSS class feature. The user won’t be having access to that area, and it’s crucial that the user can set the different classes via a metabox dropdown menu in the actual page edit mode.
Been pulling my hair for a while now, and I can’t seem to get it to work, is it impossible?
EDIT: UPDATED MY QUESTION
Your code doesn’t because the global
$post
refers to the post/page being viewed (if there is one…). What is passed withnav_menu_css_class
is a menu item – this is a particular post type. Among its properties are:object
which stores:It also stores the
object_id
So in what you want to do is check if the term actually refers to a post (or a custom post type), and then pass the
object_id
to theget_post_meta()
:Try this, not tested.
I replaced
$post->ID
with$item->ID
, should work.