Reputation: 23
I have a short piece of code that changes store images through the first gallery image.
This works great, but how do you change this code for displaying cart thumbnails as the first gallery image?
Any help or pointers to what I should be doing to achieve this would be very much appreciated.
My code:
add_action( 'woocommerce_init', 'new_replace_loop_product_thumbnail' );
function new_replace_loop_product_thumbnail() {
remove_action( 'woocommerce_before_shop_loop_item_title', 'woocommerce_template_loop_product_thumbnail', 10 );
function new_replace_product_thumbnail() {
global $product;
$attachment_id = $product->get_gallery_attachment_ids()[0];
echo "<img src='" . wp_get_attachment_url( $attachment_id ) . "'>";
}
add_action( 'woocommerce_before_shop_loop_item_title', 'new_replace_product_thumbnail', 10 );
}
Upvotes: 1
Views: 1096
Reputation: 29614
You could use the woocommerce_cart_item_thumbnail
filter hook.
Note: wp_get_attachment_image() contains several (optional) parameters with which the HTML img element that is returned can be adjusted.
Parameters
$attachment_id
(int) (Required) Image attachment ID.
$size
(string|array) (Optional) Image size. Accepts any valid image size, or an array of width and height values in pixels (in that order).
Default value: 'thumbnail'
$icon
(bool) (Optional) Whether the image should be treated as an icon.
Default value: false
$attr
(string|array) (Optional) Attributes for the image markup.
'src'
(string) Image attachment URL.
'class'
(string) CSS class name or space-separated list of classes. Default attachment-$size_class size-$size_class, where $size_class is the image size being requested.
'alt'
(string) Image description for the alt attribute.
'srcset'
(string) The 'srcset' attribute value.
'sizes'
(string) The 'sizes' attribute value.
'loading'
(string|false) The 'loading' attribute value. Passing a value of false will result in the attribute being omitted for the image. Defaults to 'lazy', depending on wp_lazy_loading_enabled().
Default value: ''
Return
(string) HTML img element or empty string on failure.
So to answer your question, you could use:
function filter_woocommerce_cart_item_thumbnail( $thumbnail, $cart_item, $cart_item_key ) {
// Get product
$product = $cart_item['data'];
// Get gallery image ids
$attachment_ids = $product->get_gallery_image_ids();
// NOT empty
if ( ! empty ( $attachment_ids ) ) {
// First
$attachment_id = $attachment_ids[0];
// New thumbnail
$thumbnail = wp_get_attachment_image( $attachment_id, 'woocommerce_thumbnail' );
}
return $thumbnail;
}
add_filter( 'woocommerce_cart_item_thumbnail', 'filter_woocommerce_cart_item_thumbnail', 10, 3 );
Upvotes: 1