How to set a background color based on post category

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