【问题标题】:Only keep in cart the last variation from WooCommerce variable products仅将 WooCommerce 可变产品的最后一个变体保留在购物车中
【发布时间】:2020-07-16 04:09:54
【问题描述】:

我有 1 个产品有 3 个变体,我一次只希望购物车中有 1 个变体来自同一个可变产品,但不想创建带有错误消息和死胡同的路障。

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

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

这是我到目前为止的想法——我已经测试过了,它可以工作,但是如果有更简单的方法或者我可能会破坏其他东西的话,我想知道

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

【问题讨论】:

    标签: php wordpress woocommerce cart product-variations


    【解决方案1】:

    以下内容只会在购物车中“静默”地保留可变产品的最后一个变体:

    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 文件中。经过测试并且可以工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-10
      • 1970-01-01
      • 2014-05-13
      • 1970-01-01
      • 2018-10-13
      • 2021-01-26
      • 1970-01-01
      • 2015-10-11
      相关资源
      最近更新 更多