I am trying to replace product image in single product page with video. I used this code, but the problem is that my video appears twice.
add_filter( 'woocommerce_single_product_image_thumbnail_html', 'replace_product_image_with_video', 10, 2 );
function replace_product_image_with_video( $html, $attachment_id ) {
global $product;
$productID = $product->get_id(); // get current product ID
// replace 11 to your specific product id
if( $productID == 11 ) {
$html = '<iframe width="650" height="420" src="https://www.youtube.com/embed/U5sLA74nAt0" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>';
}
return $html;
}
I suspect this happens because default WordPress theme I use has this code in /templates/single-product/product-thumbnails.php
echo apply_filters( 'woocommerce_single_product_image_thumbnail_html', wc_get_gallery_image_html( $attachment_id ), $attachment_id );
I dont want to overwrite this or create child themes. Is there a way to remove this filter with code somehow?
2
Answers
You can easily take care of this by injecting a script to replace the image and then remove the video from the thumb without needing a child theme.
I know you didn’t ask, but if you’re planning to do this a lot (on several different products) and don’t want to end up with spaghetti code, you should just set up a key:value pair for productIDs and the videoID and then parameterize the video ID as well since everything else should remain the same.
The problem occurs on products with multiple image, the scripts replace all the thumbnails with the video.
To show only one video, I added a condition to replace only the product featured image
Note that on the theme I use, I had to wrap the iFrame in a div otherwise it would be hidden.