I managed to solve my problem.
So, the posts are using a single.html template file (in the TwenytTwentyTwo theme: /templates/single.html).
I wanted to target a category
class in the <body>
element of the single.html.
To make that happen, I had to modify the single.html file in my Child theme by adding the following code snippet within the main wp:group
block:
<!-- wp:post-terms {"term":"category"} /-->
After that, in the functions.php I added a function that adds a category class to the post’s HTML <body>
element on the single post pages.
(I added comments to make it clear.)
// Get posts category
function add_category_class( $classes ) {
// Check if the current page being viewed is a single post
if ( is_single() ) {
// The $post variable is set to the current post being viewed
global $post;
// Loop through each category of the post, add a class "category-" to the $classes array
// Followed by the category's slug (URL-friendly)
// Each category associated with the current post, and the "get_the_category( $post->ID )" function is getting those categories based on the ID of the current post.
foreach ( ( get_the_category( $post->ID ) ) as $category ) {
$classes[] = 'category-' . $category->slug;
}
}
// Return the updated body classes array
return $classes;
}
// Add the classes to the body tag of the post
add_filter( 'body_class', 'add_category_class' );
and in the style.css I was able to target it (here the photos category is selected).
/* Change background color for posts in Photos category */
.category-photos {
background-color: red;
}
That made the background red of a single post page within a a specific category.