How to set a background color based on post category

Hi Bricks community! :wave:t2:

How can I set a specific background color e.g. for a card in a post query based on a category?

:arrow_right: So that different cards for different categories are color coded :red_circle::large_blue_circle::yellow_circle:. And they are easier to distinguish for visitors.

Only with a php-snippet or is there an easier way for a non-php-user?

Thank you very much!

Bricks regards,
Heiko

Try this:

1. Put this into your childthemes functions.php:

function getPostCatName() {
    $category = get_the_category();
    return $category[0]->slug;
}

This snippet gets the first category of a post and returns the slug. We only get the first in case a post has more than one in which case the output (our future styling selector) would change.

2.
Add a custom attribute to the the post. Not sure what you used to create your grid but basically add to whatever wraps each individual post within the grid like so:
image

3.
Now each post should have something like this:
image

We can target that in css like so:

.parent-grid-selector .single-post-child[data-category="news"] {
background: tomato;
}

.parent-grid-selector .single-post-child[data-category="someothercategory"] {
background: firebrick;
}
5 Likes

Awesome answer! Thanks a ton for all your effort, the screenshots etc.! I will try that. Very much appreciated, @manc! :pray:

you cna add color field for any taxonomy really with acf or pods plugins and use those custom fields