I want to change product image on hover on archive pages for products from Merch category. (Product cover image should be changed to first gallery photo)
I took the following code form here https://stackoverflow.com/questions/62088615/switch-product-image-on-hover-on-woocommerce-archive-page. But it affects all products:
add_action( 'woocommerce_before_shop_loop_item_title', 'add_on_hover_shop_loop_image' ) ;
function add_on_hover_shop_loop_image() {
$image_id = wc_get_product()->get_gallery_image_ids()[1] ;
if ( $image_id ) {
echo wp_get_attachment_image( $image_id ) ;
} else { //assuming not all products have galleries set
echo wp_get_attachment_image( wc_get_product()->get_image_id() ) ;
}
}
/* CUSTOM ON-HOVER IMAGE */
.woocommerce ul.products li.product a img {
/* FORMAT ALL IMAGES TO FILL EQUIVALENT SPACE,
to remove jitter on replacement */
height: 150px;
width: 150px;
object-fit: cover;
padding: 0;
margin: 0 auto;
}
.woocommerce ul.products li.product a img:nth-of-type(2) {
display: none;
}
.woocommerce ul.products li.product a:hover img:nth-of-type(2) {
display: block
}
.woocommerce ul.products li.product a:hover img:nth-of-type(1) {
display: none;
}
I'm sorry for a newbie question but I can't figure out how to apply it for 'merch' product category. My attempt:
add_action( 'woocommerce_before_shop_loop_item_title', 'add_on_hover_shop_loop_image' ) ;
function add_on_hover_shop_loop_image() {
global $product;
$product_id = $product->get_id();
if ( has_term( 'merch', 'product_cat', $product_id ) ) {
$image_id = wc_get_product()->get_gallery_image_ids()[1] ;
if ( $image_id ) {
echo wp_get_attachment_image( $image_id ) ;
}
else { //assuming not all products have galleries set
echo wp_get_attachment_image( wc_get_product()->get_image_id() ) ;
}
}
}
Thank you for your help!