首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >仅在购物车中保留WooCommerce variable产品的最新变体

仅在购物车中保留WooCommerce variable产品的最新变体
EN

Stack Overflow用户
提问于 2020-07-16 12:09:55
回答 1查看 69关注 0票数 1

我有一个产品与3个变化,我只想在购物车一次从相同的变量产品的一个变化,但不想创造一个错误消息和死胡同的障碍。

如果添加了相同的产品,我想交换变体。

因此,如果客户将Product 1变体1添加到购物车中,然后他们返回并添加相同的产品但添加了不同的变体(Product 1变体2),我希望该函数删除变体1并添加变体2。

这是我到目前为止想出来的--我已经测试过了,它可以工作,但如果有更简单的方法,或者我可能会弄坏其他东西,请注意

代码语言:javascript
复制
add_action( 'woocommerce_add_to_cart', 'check_product_added_to_cart', 10, 6 );
function check_product_added_to_cart($cart_item_key, $product_id, $quantity, $variation_id, $variation, $cart_item_data) {

    // First Variation
    $product_a = 5831;
    // Second Variation
    $product_b = 5830;
    // Third Variation
    $product_c = 5832;

    // Initialising some variables
    $has_item = false;
    $is_product_id = false;

    foreach( WC()->cart->get_cart() as $key => $item ){
        // Check if the item to remove is in cart
        if( $item['product_id'] == $product_b || $product_c ){
            $has_item = true;
            $key_to_remove = $key;
        }

        // Check if we add to cart the targeted product ID
        if( $product_id == $product_a ){
            $is_product_id = true;
        }
    }

    if( $has_item && $is_product_id ){
        WC()->cart->remove_cart_item($key_to_remove);
    }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-07-16 18:42:42

下面的代码只会在购物车中“静默”地保存变量产品的最后一个变体:

代码语言:javascript
复制
add_action('woocommerce_before_calculate_totals', 'keep_last_variation_from_variable_products', 10, 1 );
function keep_last_variation_from_variable_products( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    $parent_ids = array();

    foreach (  $cart->get_cart() as $cart_item_key => $cart_item ) {
        // Only for product variations
        if ( $cart_item['variation_id'] > 0 ) {
            // When a variable product exist already in cart
            if( isset($parent_ids[$cart_item['product_id']]) && ! empty($parent_ids[$cart_item['product_id']]) ) {
                // Remove it
                $cart->remove_cart_item($parent_ids[$cart_item['product_id']]);
            }
            // Set in the array the cart item key for variable product id key
            $parent_ids[$cart_item['product_id']] = $cart_item_key;
        }
    }
}

代码放在活动子主题(或活动主题)的functions.php文件中。经过测试,效果良好。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62927294

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档