Reputation: 699
I'm trying to replace single product page gallery images to custom placeholder I have.
I have found this hook:
woocommerce_single_product_image_thumbnail_html
But the hook using the variable $image
, which his type is unclear (html string/url).
Also found the following hook wp_get_attachment_image_src
to be responsible of the thumbnails image URL source, but it doesn't work.
add_filter( 'wp_get_attachment_image_src', array( $this, 'pn_change_product_image_link'), 50, 4 );
function pn_change_product_image_link( $image, $attachment_id, $size, $icon ){
if( ! is_product() ) return $image; // Only on single product pages
if( $size == 'shop_thumbnail' ) return $image; // Not for gallery thumbnails (optional)
// Your source image link
$new_image_id = 1370;
$src = wp_get_attachment_url( $new_image_id );
$width = ''; // <== (optional) define the width
$height = ''; // <== (optional) define the height
$image = array( $src, $width, $height );
return $image;
}
How can I replace Woocommerce gallery images to custom placeholder image?
Upvotes: 2
Views: 1915
Reputation: 4110
You are setting width and height to be blank. That's why it doesn't work.
Also, the variable $image
(first argument of the hook wp_get_attachment_image_src
) is an array structured as follows:
$image[0]
Image source URL$image[1]
Image width in pixels$image[2]
Image height in pixels$image[3]
Whether the image is a resized imageFinally, you are using the size shop_thumbnail
which has been removed from WooCommerce.
These sizes will be removed in WooCommerce 4.6.0:
shop_catalog
,shop_single
,shop_thumbnail
.
Use these:
woocommerce_thumbnail
Used in product listings. We assume these work for a 3 column grid layout.woocommerce_single
Used on single product pages for the main image.woocommerce_gallery_thumbnail
Used below the main image on the single product page to switch the gallery.You can optimize your function like this:
add_filter( 'wp_get_attachment_image_src', 'pn_change_product_image_link', 50, 4 );
function pn_change_product_image_link( $image, $attachment_id, $size, $icon ) {
// only on single product pages
if ( ! is_product() ) {
return $image;
}
// not for gallery thumbnails (optional)
if ( $size == 'woocommerce_thumbnail' ) {
return $image;
}
// always shows the site logo
$logo_image_id = 240; // set here the id image of your logo
if ( $attachment_id == $logo_image_id ) {
return $image;
}
// set the new attachment id
$new_image_id = 1370;
// set the new image url
$image[0] = wp_get_attachment_url( $new_image_id );
return $image;
}
The code has been tested and works.
USEFUL LINKS
Upvotes: 2