I want to add a custom class to the categories on the product archive page so that I can add custom styles to the categories tags.
Example:
Product X in Category 1 --> Category Tag in Yellow
Product Y in Category 2 --> Category Tag in Red
I'm using this php snippet, but this is for single product pages and is applied to the <body>
element. How can I change it to work for shop archive pages as well?
add_filter( 'body_class','my_body_classes2' );
function my_body_classes2( $classes ) {
if ( is_product() ) {
global $post;
$terms = get_the_terms( $post->ID, 'product_cat' );
foreach ($terms as $term) {
$product_cat_id = $term->term_id;
$classes[] = 'product-in-cat-' . $product_cat_id;
}
}
return $classes;
}
CodePudding user response:
You can use the newer woocommerce_post_class
filter hook
So you get:
/**
* WooCommerce Post Class filter.
*
* @since 3.6.2
* @param array $classes Array of CSS classes.
* @param WC_Product $product Product object.
*/
function filter_woocommerce_post_class( $classes, $product ) {
// Returns true when viewing a product category archive.
// Returns true when on the product archive page (shop).
if ( is_product_category() || is_shop() ) {
// Set taxonmy
$taxonomy = 'product_cat';
// Get the terms
$terms = get_the_terms( $product->get_id(), $taxonomy );
// Error or empty
if ( is_wp_error( $terms ) || empty( $terms ) ) {
return $classes;
}
// Loop trough
foreach ( $terms as $index => $term ) {
// Product term Id
$term_id = $term->term_id;
// Add new class
$classes[] = 'product-in-cat-' . $term_id;
}
}
return $classes;
}
add_filter( 'woocommerce_post_class', 'filter_woocommerce_post_class', 10, 2 );
Note: the if condition can be extended/constrained with other conditional tags
Example:
is_product()
- Returns true on a single product page. Wrapper for is_singular.- etc..
To NOT apply this, use
!
in the if condition:
// NOT if ( ! is_product_category() )..