This is my first post here. I am struggling with a new situation for me, as a WP Developer.
I have a loop that lists some posts. These posts can be published in different categories. I need to style the name of the displayed category based on which category it is. For example: Video will be written with black background and white text-color. Audio will be written with green background and white text-color.
I need to get the name of the category and apply a CSS class. Here is my current fragment of code:
<div class="row">
<?php
$args = array('post_type'=>'post', 'showposts'=>8, 'category_name'=>'noticias');
$noticias = get_posts($args);
if($noticias) : foreach($noticias as $post) : setup_postdata($post);
?>
<div class="col-xl-3 col-lg-4 col-md-4 col-sm-6 n-container-sm">
<h3 class="titulo_post_pequeno">
<a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a>
</h3>
<p><span class="categoria_post cat-geral"><?php foreach((get_the_category()) as $category) { echo $category->cat_name;}?></span> / <span class="date-post-peq">EM <?php the_time('d/m/y'); ?></span></p>
<a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>">
<?php if ( has_post_thumbnail() ) {
the_post_thumbnail('img-noticia', ['class'=>'img-fluid img-destaque'] );
} else {
echo '<img class="img-fluid img-destaque" src="'.get_bloginfo("template_url").'/img/none_noticia.jpg">';
}
?>
</a>
<a href="<?php the_permalink(); ?>" class="btn btn-primary btn-read">Leia +</a>
</div>
<?php
endforeach;
endif;
?>
</div>
foreach((get_the_category()) as $category)echoing anything? If it's giving you the categories, I'd suggest moving it to the outer div. Just place it inside of the class list and then you'll also have the category name as a class on the outer div, which you can target for styling.