在 Woocommerce 购物车中显示特定产品 ID 的自定义缩略图

Display a custom thumbnail for a specific product ID in Woocommerce cart

在 Woocommerce 中,我想用个性化图片更改特定的购物车项目缩略图。我可以更改图像,但它会更改所有购物车项目缩略图。
我只想更改特定产品ID的图像。

我该怎么做?

这是我使用的代码:

add_filter( 'woocommerce_cart_item_thumbnail', 'change_woocommerce_cart_item_thumbnail', 10, 3 ); 

function change_woocommerce_cart_item_thumbnail( $thumbnail, $cart_item, 

    $cart_item_key ) { 

    $cart = WC()->cart->get_cart();

    foreach( $cart as $cart_item ){

        $product = wc_get_product( $cart_item['product_id'] );

        if($cart_item['product_id'] == 75){

        echo  'New Image Here';

        }
    }

};

请帮忙。

您不需要 foreach 循环,因为 $cart_item 已作为参数包含在函数中。以下代码适用于所有产品类型,并允许您在购物车页面中拥有特​​定产品的自定义缩略图:

add_filter( 'woocommerce_cart_item_thumbnail', 'change_woocommerce_cart_item_thumbnail', 20, 3 ); 
function change_woocommerce_cart_item_thumbnail( $thumbnail, $cart_item, $cart_item_key ){ 
    // HERE your targeted product ID
    $targeted_id = 75;

    if( $cart_item['product_id'] == $targeted_id || $cart_item['product_id'] == $targeted_id ){
        echo  'New Image Here';
    }
}

代码进入您的活动子主题(或活动主题)的 function.php 文件。已测试并有效。

LoicTheAztec 的解决方案很棒,但是除了符合 if 语句中的条件的缩略图外,所有缩略图都会留空。它让我完成了 90% 的工作。为了克服这个问题,我添加了...

echo $thumbnail;

添加后(在 if 块之外)您可以看到所有缩略图以及您的自定义缩略图。 LoicTheAztec 解决方案也有一个 OR 运算符,但因为它使用与 OR 之前的第一个条件完全相同的条件,所以不需要它。也许它只是您需要满足多个条件的场景的占位符。

在这种情况下,switch 语句似乎是更好的选择。它允许您以非常易读的方式轻松自定义任意数量的缩略图。这是对我有用的最终代码...

add_filter( 'woocommerce_cart_item_thumbnail', 'aw_change_woocommerce_cart_item_thumbnail', 20, 3 );
function aw_change_woocommerce_cart_item_thumbnail( $thumbnail, $cart_item, $cart_item_key ){
  $theProductID = $cart_item['product_id']; // save product ID into a variable
  switch ($theProductID) {
    case 47056:
      //this is a gift membership which needs a different shaped thumbnail than other products;
    echo '<img width="73" height="46" src="/wp-content/uploads/2020/05/giftcard-thumb.jpg" class="attachment-woocommerce_thumbnail size-woocommerce_thumbnail" alt="gift card">';
    break;
    case 47149:
      //this is a gift card which also needs a different shaped thumbnail than other products;
    echo '<img width="73" height="46" src="/wp-content/uploads/2020/05/giftcard73x58.jpg" class="attachment-woocommerce_thumbnail size-woocommerce_thumbnail" alt="gift card">';
    break;
    default:
    echo $thumbnail;
  }
}