【问题标题】:Keep in cart only last added item from specific product category in WooCommerce仅将 WooCommerce 中特定产品类别中最后添加的商品保留在购物车中
【发布时间】:2020-12-10 00:59:00
【问题描述】:

我有一种情况,用户不能从特定类别将超过 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;
    }
}

有什么帮助吗?

【问题讨论】:

  • 在工作版本中,无论如何您都返回 true - 在第二个版本中,您现在仅在类别为测试时才这样做。

标签: php wordpress woocommerce cart taxonomy-terms


【解决方案1】:

试试这个。

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

【讨论】:

  • 它的工作,但它不允许添加同一类别的另一个产品,它应该用最新添加到购物车的项目替换购物车?
  • 您要覆盖同一类别的产品吗?
  • 没错,用最后添加到购物车的商品覆盖
  • 没用,它允许我添加同一类别的产品
【解决方案2】:
function custom_maybe_empty_cart( $valid, $product_id, $quantity ) {

foreach ( WC()->cart->get_cart() as $cart_item ){
    if( has_term( 'test', 'product_cat', $cart_item['product_id'] ) ) {
  if( ! empty ( WC()->cart->get_cart() ) && $valid ){
    WC()->cart->empty_cart();
    wc_add_notice( 'Only allowed 1 item in cart.', 'error' );
  }
}
 }
 return $valid;
  }
add_filter( 'woocommerce_add_to_cart_validation', 'custom_maybe_empty_cart', 10, 3 );

此代码对我有用。非常感谢大家的帮助。

【讨论】:

    猜你喜欢
    • 2019-09-18
    • 2021-07-22
    • 2019-01-27
    • 2017-12-10
    • 1970-01-01
    • 2018-06-03
    • 2018-08-07
    • 1970-01-01
    • 2018-07-05
    相关资源
    最近更新 更多