仅在购物车中保留WooCommerce中特定产品类别的最后添加的商品

问题描述

我遇到这样的情况,用户不能从特定类别的购物车中添加超过1种产品。我尝试使用woocommerce_add_to_cart_validation过滤器挂钩。

此代码适用于所有商品,并保留在购物车中最后添加的商品中:

// before add to cart,only allow 1 item in a cart
add_filter( 'woocommerce_add_to_cart_validation','woo_custom_add_to_cart_before' );

function woo_custom_add_to_cart_before( $cart_item_data ) {
    global $woocommerce;
    
    $woocommerce->cart->empty_cart();
    
    // Do nothing with the data and return
    return true;
}

此代码无效:

add_filter( 'woocommerce_add_to_cart_validation','woo_custom_add_to_cart_before' );

function woo_custom_add_to_cart_before( $cart_item_data ) {
    if( is_product_category( 'test' ) ) {
        global $woocommerce;
        $woocommerce->cart->empty_cart();

        // Do nothing with the data and return
        return true;
    }
}

请帮忙吗?

解决方法

尝试一下。

add_action( 'woocommerce_before_calculate_totals','only_allow_one_item_from_specific_category',10,1 );
function only_allow_one_item_from_specific_category( $cart ){
    foreach ( $cart->get_cart() as $cart_item_key => $cart_item ){
        if( has_term( 'test','product_cat',$cart_item['product_id'] ) ) {
            $cart->remove_cart_item( $cart_item['product_id'] );
        }
    }
}
,
{{1}}

此代码对我有用。非常感谢您对所有人的帮助。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...