Event Organiser uses the event category colours for the calendar shortcode and the agenda widget – it’ll also be using them in the coming soon add-on, ‘Event board’:
But there is no reason why they can’t be used elsewhere in your theme and in this post I’ll be showing you how you can print CSS classes to your header
which allow you to target parts of your website and colour them according to the category. As an example we’ll be setting the background colour (but it could be border colour, or front colour etc).
The hook you use for this is the wp_print_styles
action which fires just before your stylesheets are loaded (you could use wp_head
instead to print our custom CSS)
Please note we are printing styles directly, which is why we are using wp_print_styles
. You should not enqueue or register scripts or styles on wp_print_styles
. See this post for more information.
The following function gets all the category terms, loops through them and prints a CSS rule for each term of the form:
.event-category-{Term ID}{
background: {Category colour}
}
We can then apply the class .event-category-7
to colour the background of a DOM element with the colour of the event category with ID 7. (Of course doing this manually will be tedious and a pain to maintain – so you should try to add these styles programatically).
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-%d{ background: %s;}\n",
$cat->term_id,
eo_get_category_color( $cat )
);
}
echo '</style>';
}
}
Or you may prefer to use the category slug rather than ID:
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-%s{ background: %s;}\n",
sanitize_html_class( $cat->slug ),
eo_get_category_color( $cat )
);
}
echo '</style>';
}
}
Note that this second example differs in three ways:
- Obviously, we’ve used
$cat->slug
instead of$cat->term_id
. - We’ve added
sanitize_html_class()
to ensure that the slug is safe to use as a class name (it should be, but better safe than sorry) - We’ve replaced
.event-category-%d
with.event-category-%s
– so that the slug isn’t cast as an integer.