Add On-Hover Image from Galleries for WooCommerce Shop Page

Answer at Stackoverflow:

What I think you’ll want to do, assuming your installation is a somewhat standard WooC installation, is utilize the loop item action hook to add the desired on-hover image.

/**
 * Add image to default WooCommerce Shop Archive
 * to be used as on-hover alternative image
 */
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() ) ;
 } 
}

Preliminary CSS:

/* 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;
}

The above will get what you want for one type of shop archive display, to achieve a simple replacement, but there will be numerous particulars that you may need or want to customize for your site. 150x150px may not be the right size for your theme, for example. Or you may decide you need to replace the default image completely with a different set, and that to get a particular transition effect, or to get consistency with other effects in use on your site, you’ll need a different approach to CSS and possibly to javascript.

From StackOverflow comments:

  • Awesome, this is working, thank you very much. Unfortunatly it prints the 150x150px version of the gallery image. Do you know to get the better quality image with 600x600px? CSS isnt the solution. – Krystian Manthey Jun 5 at 7:28
  •  
    Sure – wp_get_attachment_image() defaults to ‘thumbnail’. If your theme has 600×600 alreqady registered as an image size ( ‘medium’?, ‘large’?), then just add it as second parameter. or try ‘array( ‘600’, ‘600’ ) (and adjust CSS appropriately) – More with examples at developer.wordpress.org/reference/functions/… – CK MacLeod Jun 5 at 7:35    
  •  
    (“medium” and “large” would more likely be set in installation Settings/Media) – CK MacLeod Jun 5 at 7:42   

Leave a Reply