限制 WooCommerce 购物车中允许的不同产品数量

时间:2021-04-26 00:31:48

标签: php wordpress woocommerce product cart

使用 Limit the number of cart items in Woocommerce 答案,我可以限制我商店购物车页面中的总产品数量。但我需要限制购物车中不同商品的数量,但保持数量不受限制并限制产品总价金额。

例如,我的购物车中有 10 件商品,但总产品数量为 50,总产品价格金额为 5000。 如果我在购物车 10 中设置了不同的产品数量和总价金额 5000,我的客户就无法将另外一种产品添加到他们的购物车中。

我该怎么做?

1 个答案:

答案 0 :(得分:2)

您可以使用以下方法来限制允许添加到购物车的不同产品的数量:

// Checking and validating when products are added to cart
add_filter( 'woocommerce_add_to_cart_validation', 'only_n_products_allowed_in_cart', 10, 3 );
function only_n_products_allowed_in_cart( $passed, $product_id, $quantity ) {
    $items_limit = 10;
    $total_count = count( WC()->cart->get_cart() ) + 1;

    if( $total_count > $items_limit ){
        // Set to false
        $passed = false;
        // Display a message
         wc_add_notice( sprintf( __( "You can’t have more than %s different products in cart", "woocommerce" ), $items_limit ), "error" );
    }
    return $passed;
}

代码位于活动子主题(或活动主题)的functions.php 文件中。