根据数量/类别在 WooCommerce 迷你购物车中添加自定义图像

Adding custom Images in WooCommerce mini-cart based on quantity / category

可能是一个基本的问题,我离解决它只差一点点了。 本质上,我正在建立一个在线商店,以每箱 12 个为增量销售啤酒瓶,可以选择混合 7 种不同啤酒中的任何一种。目前,我已启用迷你购物车来显示装满的箱子 - 一瓶一瓶 - 每瓶都添加,这是基于购物车总数。

<?php if( WC()->cart->get_cart_contents_count() == 0){ 
    echo '<img src="***image-with-0-bottles" alt="icon" />';
} 

elseif( WC()->cart->get_cart_contents_count() == 1){ 
    echo '<img src="***image-with-1-bottle.png" alt="icon" />';
}

elseif( WC()->cart->get_cart_contents_count() == 2){ 
    echo '<img src="***image-with-2-bottle2.png" alt="icon" />';
}

等等等等。

以上可能是一种不必要的复杂方法,但主要关注的是,仅当将一个特定类别添加到购物车时才需要进行上述操作,即。仅适用于单瓶。如果将任何其他类别添加到购物篮中,我希望图像保持不变,并且只有在添加 'single-bottle' 时才会更改。

有点新。有点卡住了。位PHP——可怜!我已经尝试了很多我读过的东西,但我真的不具备真正了解自己立场的知识。非常欢迎任何帮助。

当您显示迷你购物车模板的代码时,您有关于缩略图的信息 (line 38):

$thumbnail = apply_filters( 'woocommerce_cart_item_thumbnail', $_product->get_image(), $cart_item, $cart_item_key );

这意味着您可以操纵迷你购物车缩略图。

但对于您的特殊产品类别,因为它基于总购物车数量,您将在该产品类别的所有项目上获得相同的图像。

这是该代码的示例:

add_filter( 'woocommerce_cart_item_thumbnail', 'custom_cart_item_thumbnail', 10, 3 );
function custom_cart_item_thumbnail( $thumbnail, $cart_item, $cart_item_key ){
    // Only for Mini Cart
    if( is_cart() ) return $thumbnail;

    $product = $cart_item['data'];
    $product_id = $product->get_id();
    $cart_item_count = WC()->cart->get_cart_contents_count();

    // Set here your product category like 'case-dozen'
    if( has_term( 'case-dozen', 'product_cat', $product_id ) ){
        // Total cart item count based
        if ( 0 == $cart_item_count )
            $thumbnail = '<img src="/image-with-0-bottles.png" alt="icon" />';
        elseif ( 1 == $cart_item_count )
            $thumbnail = '<img src="/image-with-1-bottle.png" alt="icon" />';
        elseif ( 2 == $cart_item_count )
            $thumbnail = '<img src="/image-with-2-bottle2.png" alt="icon" />';
    }
    return $thumbnail;
}

代码进入您的活动子主题(或主题)的 function.php 文件或任何插件文件。

这应该有效。