Skip to content
Advertisement

Switch product image on hover on WooCommerce archive page

Is there a way (maybe via functions.php) to change the product-image in woocommerce shops (archive page) on hover with the first attached gallery image of the product? I cannot find how to target both. I guess it must be sth like this:

add_action( 'woocommerce_shop_loop_item', 'change_image_on_hover', 10 );
function change_image_on_hover() {
     $product->get_gallery_image_ids();
     print 'woocommerce_gallery_image';
}

enter image description here

Advertisement

Answer

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_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.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement