2015-10-14 119 views
1

我在下面限制了woocommerce的订单,限制为5件商品。当他们尝试通过超过5项的结帐时,它会弹出一条消息告诉他们,然后他们必须删除项目。我想知道的是,如果有一种方法,他们不能在篮子中添加超过5件物品?限制woocommerce购物篮的尺寸

add_action('woocommerce_check_cart_items', 'set_max_num_products'); 
function set_max_num_products() { 
// Only run in the Cart or Checkout pages 
if(is_cart() || is_checkout()) { 
    global $woocommerce; 

    // Set the max number of products before checking out 
    $max_num_products = 5; 
    // Get the Cart's total number of products 
    $cart_num_products = WC()->cart->cart_contents_count; 

    // A max of 5 products is required before checking out. 
    if($cart_num_products > $max_num_products) { 
     // Display our error message 
     wc_add_notice(sprintf('<strong>A maxiumum of %s samples are allowed per order. Your cart currently contains %s.</strong>', 
      $max_num_products, 
      $cart_num_products), 
     'error'); 
    } 
} 
} 

回答

1

每个产品在加入购物车之前都必须经过验证。您可以通过woocommerce_add_to_cart_validation过滤器修改验证状态,从而控制是否将其添加到购物车。

function so_33134668_product_validation($valid, $product_id, $quantity){ 
    // Set the max number of products before checking out 
    $max_num_products = 5; 
    // Get the Cart's total number of products 
    $cart_num_products = WC()->cart->cart_contents_count; 

    $future_quantity_in_cart = $cart_num_products + $quantity; 

    // More than 5 products in the cart is not allowed 
    if($future_quantity_in_cart > $max_num_products) { 
     // Display our error message 
     wc_add_notice(sprintf('<strong>A maxiumum of %s samples are allowed per order. Your cart currently contains %s.</strong>', 
      $max_num_products, 
      $cart_num_products), 
     'error'); 
     $valid = false; // don't add the new product to the cart 
    } 
    return $valid; 
} 
add_filter('woocommerce_add_to_cart_validation', 'so_33134668_product_validation', 10, 3); 
+0

只是想知道我们可以使用'$ PRODUCT_ID其中$的product_id =(INT)(apply_filters( 'woocommerce_add_to_cart_product_id',$ _GET [ '添加到购物车'])?apply_filters( 'woocommerce_add_to_cart_product_id',$ _GET ['add-to-cart']):apply_filters('woocommerce_add_to_cart_product_id',$ _POST ['add-to-cart']));'刚刚添加的产品并限制其数量? –

+0

不知道你在问什么。 – helgatheviking

+0

如果我们可以检索刚添加到购物车的产品及其数量,与购物车数量进行比较,并让客户知道他为什么不能添加更多产品。这是我问的。 –