Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
1.9 kB
5
Indexable
Never
PHP CODE
// Remove default WooCommerce product image output
remove_action( 'woocommerce_before_shop_loop_item_title', 'woocommerce_template_loop_product_thumbnail', 10 );

// Add custom image hover swap functionality
add_action( 'woocommerce_before_shop_loop_item_title', 'custom_product_image_hover_swap', 10 );

function custom_product_image_hover_swap() {
    global $product;

    $gallery = $product->get_gallery_image_ids();
    $main_image_url = wp_get_attachment_image_url( get_post_thumbnail_id(), 'woocommerce_thumbnail' );

    // Only add hover swap if there is a gallery image
    if ( $gallery ) {
        $hover_image_url = wp_get_attachment_image_url( $gallery[0], 'woocommerce_thumbnail' );

        echo '<span class="et_shop_image">';
        echo '<div class="product-image-hover-swap">';
        echo '<img src="' . esc_url( $main_image_url ) . '" class="main-image" />';
        echo '<img src="' . esc_url( $hover_image_url ) . '" class="gallery-image" />';
        echo '</div>';
        echo '<span class="et_overlay"></span>';
        echo '</span>';
    } else {
        // In case there is no gallery image, just show the main product image
        echo '<span class="et_shop_image">';
        echo '<img src="' . esc_url( $main_image_url ) . '" class="attachment-woocommerce_thumbnail size-woocommerce_thumbnail" alt="" />';
        echo '<span class="et_overlay"></span>';
        echo '</span>';
    }
}




CSS CODE
.woocommerce ul.products li.product .product-image-hover-swap img {
    transition: opacity 0.4s ease;
}

.woocommerce ul.products li.product .product-image-hover-swap img.gallery-image {
    opacity: 0;
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
}

.woocommerce ul.products li.product .product-image-hover-swap:hover img.gallery-image {
    opacity: 1;
}

.woocommerce ul.products li.product .product-image-hover-swap:hover img.main-image {
    opacity: 0;
}
Leave a Comment