1- Add the PHP code share in last
2- Add the shortcode in place of featured image in loop grid - [second_product_image]
Code:
// Shortcode to output first and second WooCommerce product image with hover effect and link
function custom_second_image_shortcode() {
global $product;
if (!$product || !is_a($product, 'WC_Product')) return '';
$main_image_url = wp_get_attachment_url($product->get_image_id());
$product_link = get_permalink($product->get_id());
$gallery = $product->get_gallery_image_ids();
if (empty($gallery)) return ''; // Exit if no gallery image
$second_image_url = wp_get_attachment_url($gallery[0]);
ob_start();
?>
<a href="<?php echo esc_url($product_link); ?>" class="hover-image-wrapper">
<img class="product-main-image" src="<?php echo esc_url($main_image_url); ?>" alt="<?php echo esc_attr($product->get_name()); ?>" />
<img class="product-hover-image" src="<?php echo esc_url($second_image_url); ?>" alt="<?php echo esc_attr($product->get_name()); ?>" />
</a>
<?php
return ob_get_clean();
}
add_shortcode('second_product_image', 'custom_second_image_shortcode');
// Enqueue CSS for image hover and sizing
add_action('wp_enqueue_scripts', function () {
wp_add_inline_style('elementor-frontend', '
.hover-image-wrapper {
position: relative;
display: block;
max-height: 300px;
overflow: hidden;
text-decoration: none;
}
.hover-image-wrapper img {
display: block;
width: 100%;
height: 300px;
object-fit: cover;
object-position: center center;
transition: opacity 0.4s ease;
}
.hover-image-wrapper .product-hover-image {
position: absolute;
top: 0;
left: 0;
opacity: 0;
}
.hover-image-wrapper:hover .product-hover-image {
opacity: 1;
}
.hover-image-wrapper:hover .product-main-image {
opacity: 0;
}
');
});