Adding event colour to your menu

In my last post I showed you how to dynamically print CSS to enable you to target parts of your site and colour them according to event category. In this post I’ll be showing an explicit example of how to use that to colour your menu items.

If you need to get a colour corresponding to an event (rather than from the category directly), then you can use eo_get_event_color(). See the docs.

First, we’ll use the following (based on this tutorial) to add rules for our category-specific classes,

add_action( 'wp_print_styles', 'my_print_event_cat_colours' );
function my_print_event_cat_colours(){

    $cats = get_terms( 'event-category' );
    if( $cats ){

        echo '<style>';
        foreach( $cats as $cat ){
                printf( 
                    ".event-category-menu-item-%d{ background: %s;}\n", 
                    $cat->term_id, 
                    eo_get_category_color( $cat ) 
                );  
        }
        echo '</style>';
    }
}

Now we want to add the appropriate class to any menu item which points to an event category. We could do this manually (WordPress allows you to manually add classes to menu items) – but that is tedious and would need to maintained as you add and remove categories.

Instead we can use the nav_menu_css_class hook. As you may have guessed it filters an array of classes which will be applied to a menu item.

add_filter( 'nav_menu_css_class' , 'my_add_classes_to_event_cat_menu_items' , 10 , 2 );
function my_add_classes_to_event_cat_menu_items( $classes, $item ){
        //Add or remove classes to $classes array
    return $classes;
} 

It also passes the menu item, $item, as a second argument allowing us to conditionally add classes to it. Now, menu items are in fact a post type, so $item contains all the usual ‘post’ information, but menu items typically point to something on your site (a page, a category term, etc) – and it also contains data pertaining to that object it points to. Specifically:

  • $item->object stores the object the menu item refers to, e.g. ‘post’, ‘page’, ‘my-cpt’, or ‘my-taxonomy’ (the post type name, or the taxonomy name)
  • $item->type stores what ‘type’ of object is it, either: ‘post_type’ or ‘taxonomy’.
  • $item->object_id references the ID of the object (post ID, term ID etc).

We can use this to first check that a menu item points to an event category term and if it does, add the class event-category-menu-item-{Term ID} to it:

add_filter( 'nav_menu_css_class' , 'my_add_classes_to_event_cat_menu_items' , 10 , 2 );
function my_add_classes_to_event_cat_menu_items( $classes, $item ){

    if(  $item->object == 'event-category' ){
        $classes[] = 'event-category-menu-item-' . $item->object_id;
    }
    return $classes;
}