Setting Event Colors By Taxonomy Term or CPT

Pie Calendar Pro allows you to set an event color and event text color per event.

Sometimes, however, you might want all events belonging to a specific taxonomy term to have the same color.

This can be achieved via the piecal_event_array_filter hook, which allows us to modify event properties before they're output.

Here's an example, which sets all events that belong to the "Green Events" category to have a green color (dot for normal events, and background for all-day events) and red text color.

// This hook allows us to filter and change event properties.
add_filter('piecal_event_array_filter', function( $event ) {
    // Here, we pass the taxonomy name 'category', because we want to check which categories the post belongs to.
    $taxonomy = 'category';
    // Next, we get a list of terms from this category that have been assigned to this event.
    $termList = get_the_terms( $event['postId'], $taxonomy );

    // If there are no categories, it will return null, so we return early when $termList is not an array.
    if( !is_array( $termList ) ) return $event;

    // Next we simplify our term list into a list of just the term slugs.
    $termSlugs = array_map( function( $item ) { return $item->slug; }, $termList );

    // Finally, we can use normal conditional logic to set the event's color and textColor properties depending on whether specific term slugs are in the $termSlugs array

    // Here we've simplified the logic by creating color maps where we can map specific slugs to specific colors and textColors.
    $slugColorMap = [
        'green-events' => 'green',
        'pink-events' => 'pink'
    ];

    $slugTextColorMap = [
        'green-events' => 'red',
        'pink-events' => 'white'
    ];

    // Now we loop through the slugs and assign the colors according to the maps.
    foreach( $termSlugs as $term ) {
        if( in_array( $term, $termSlugs ) ) {
            $event["color"] = $slugColorMap[$term];
        }

        if( in_array( $term, $termSlugs ) ) {
            $event["textColor"] = $slugTextColorMap[$term];
        }
    }

    return $event;
}, 11);

This example is basic, but provides the foundation for advanced modification of events based on their taxonomy terms.

Set Colors by Custom Post Type

If you want to set a specific color for all events in a given post type, you can use the simple snippet below.

Be sure to change "event-nr" in the example code below to the slug of your custom post type. The color values can either be a color phrase like "orange" or a color code such as hex, rgb, etc.

add_filter('piecal_event_array_filter', function( $event ) {
    if (get_post_type($event['postId']) === 'event-nr') {
        $event["color"] = 'orange';
        $event["textColor"] = 'black';
    }

    return $event;
}, 11);
Did this answer your question? Thanks for the feedback There was a problem submitting your feedback. Please try again later.