首页 > 解决方案 > 仅将 WooCommerce 可变产品的最后一个变体保留在购物车中

问题描述

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

标签: phpwordpresswoocommercecartproduct-variations

解决方案


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

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 文件中。测试和工作。


推荐阅读