在 WooCommerce 购物车中显示第一个图库图像作为产品缩略图

Display first gallery image as product thumbnail in WooCommerce cart

我有一小段代码可以通过第一个图库图像更改商店图像。

效果很好,但是如何更改此代码以将购物车缩略图显示为第一个图库图像?

任何帮助或指示我应该如何实现这一点将不胜感激。

我的代码:

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 );
}

您可以使用 woocommerce_cart_item_thumbnail 过滤器钩子。

注意:wp_get_attachment_image() 包含几个(可选)参数,可以使用这些参数调整返回的 HTML img 元素。

参数

  • $attachment_id

    (int)(必填)图像附件 ID。

  • $size

    (string|array) (可选)图像大小。接受任何有效的图像大小,或以像素为单位的宽度和高度值数组(按此顺序)。

    默认值:'thumbnail'

  • $icon

    (bool)(可选)图像是否应被视为图标。

    默认值:假

  • $attr

    (string|array)(可选)图像标记的属性。

    • 'src'

      (字符串) 图片附件 URL.

    • 'class'

      (字符串)CSS class 名称或 space 分隔的 class 列表。默认附件-$size_class 大小-$size_class,其中$size_class 是请求的图像大小。

    • 'alt'

      (字符串)alt 属性的图像描述。

    • 'srcset'

      (string) 'srcset' 属性值。

    • 'sizes'

      (string) 'sizes' 属性值。

    • 'loading'

      (string|false) 'loading' 属性值。传递 false 值将导致图像省略该属性。默认为 'lazy',取决于 wp_lazy_loading_enabled()

      默认值:''

Return

(string) HTML img 元素或失败时为空字符串。



所以要回答您的问题,您可以使用:

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 );