In WooCommerce, I want to display the category name on shop pages as well as a single product pages, for 5 categories, setting up a different background color.
I used the code in WP snippet code:
function show_category_on_loop() {
global $product;
$terms = get_the_terms( $product->get_id(), 'product_cat' );
if( $terms ) {
$names = array();
foreach ( $terms as $term ) {
$names[] = $term->name;
}
print '<span class="category-text"> '.join( ', ', $names ).'</span>'.PHP_EOL;
}
}
Plus the CSS style in customizer: .category.text {background...}
It works, but it changes the background color on all my products.
I've also tried this code, but the result is similar:
function category_single_product(){
$product_cats = wp_get_post_terms( get_the_ID(), 'product_cat' );
if ( $product_cats && ! is_wp_error ( $product_cats ) ){
$single_cat = array_shift( $product_cats );
?>
<h2 itemprop="name" class="product_category_title"><span><?php echo $single_cat->name; ?></span></h2>
<?php
}
}
add_action( 'woocommerce_before_shop_loop_item_title', 'category_single_product', 25 );
What needs to be added so that each category has its own style?? Thanks in advance, I'm not a programmer.
Hello. Both codes work. Thank you. But... I used the second method. But I encountered a problem - the products in the store have 3 categories added: 1 - category type - product line, i.e. name of the product line category (this is what I have currently done thanks to your help) 2 - category type - what body part it is for - BODY or HEAD values 3 - category type - home or professional use
How can you combine two categories (1) and (2) together by separating them with the special character "|" e.g. SUPER LINE | Body?
How can you add a note that the product is for home or professional use? Thank you in advance for your help.

first modify your php code to this:
then in your css something like this: