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.
2
Answers
first modify your php code to this:
then in your css something like this:
First, add the following CSS styles in the customizer (or in your child theme style.css file), defining for each category slug the desired color.
Here, the first rule is the default background color fallback (and text color if needed).
Then you will use the following to display the colored product category(ies) on products loop and single products, after the product title:
Code goes on functions.php file of your child theme (or in a plugin). Tested and works.
Note:
You can change the displayed location by tuning the hook priority in the add_action() function.