Woocommerce 在购物车项目中重复产品而不增加产品数量

问题描述 投票:0回答:1

我正在尝试在我的网站上执行 BOGO,场景是当有人将数量为 5 的产品添加到购物车或有人在购物车页面中增加特定购物车项目数量大于 5 时,自动在购物车页面上添加购物车项目将复制并添加为购物车商品,小计为 0.00$。这是例子

产品 数量 小计
T 恤 5 10.00$
T 恤 1 免费

我已经在我的插件页面上尝试过这个..

add_filter('woocommerce_update_cart_action_cart_updated', 'on_action_cart_updated');

function on_action_cart_updated( $cart_updated ) {

    if ( WC()->cart ) {

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

        foreach ( $cart_items as $key => $cart_item ) {
            if ( $cart_item && 5 <= $cart_item['quantity'] ) {
                $unique_key = md5( microtime().rand() );
                $duplicate_item = $cart_item;
                $duplicate_item['key'] = $unique_key;
                $duplicate_item['quantity'] = 1;

                $item_object = $cart_item['data'];
                $item_object->add_meta_data('duplicated','yes');

                $_product = wc_get_product( $cart_item );
                error_log( $_product->get_type() );
//                $product =  new WC_Product_Simple();
//                $product->set_title('')
//                //$item_object->get_meta_data('duplicated');
//
//                WC()->cart->add_to_cart( $cart_item['product_id'], 1, 0, 0, [], $unique_key);
                WC()->cart->add_to_cart($cart_item['product_id'],1);
//                WC()->cart->cart_contents[$unique_key] = $duplicate_item;
            }
        }
    }

    return $cart_updated;
}

此代码将增加旧购物车商品的数量,而不是将新购物车商品添加为购物车列表中重复的旧购物车商品。

woocommerce plugins product hook-woocommerce cart
1个回答
0
投票

尝试使用以下内容代替:

add_filter('woocommerce_update_cart_action_cart_updated', 'action_on_cart_updated');
function action_on_cart_updated( $cart_updated ) {
    $cart = WC()->cart;

    if ( ! $cart->is_empty() ) {
        foreach ( $cart->get_cart() as $item_key => $item ) {
            if ( $item && 5 <= $item['quantity'] ) {
                $item['data']->add_meta_data('duplicated', 'yes');
                $cart->set_quantity( $item_key, ($item['quantity'] - 1), false );

                $item_data = ['unique_key' => md5(microtime().rand())];
                $item_key_free = $cart->add_to_cart($item['product_id'], 1, $item['variation_id'], $item['variation'], $item_data);
            }
        }
        $cart_items = $cart->get_cart();

        if( isset($item_key_free) && isset($cart_items[$item_key_free]) ) {
            $product_name = $cart_items[$item_key_free]['data']->get_name();
            $cart_items[$item_key_free]['data']->set_name($product_name.' (FREE)');
            $cart_items[$item_key_free]['data']->set_price(0);
        }
    }
    return $cart_updated;
}

代码位于子主题的functions.php 文件中(或插件中)。应该可以。

© www.soinside.com 2019 - 2024. All rights reserved.