问题
My ecommerce
made with WooCommerce
sells 12 ready meals.
The customer can also purchase only 1 meal per type. But it must necessarily reach the exact sum of:
5 or 12 or 24 or 36 products.
Why?
Ready meals are shipped in isothermal boxes that contain a precise number of ready meals.
There are 4 types of isothermal boxes and they contain:
- 5 meals, 12 meals, 24 meals or 36 meals
So I have to force to buy only 5, 12, 24, or 36 meals at checkout on the cart page.
This figure can also be reached by adding for example 2 meals A + 3 meals B
The important thing is that if, for example, they try to buy 6 3A + 3B products, the checkout button disappears and an alarm comes out that says:
You can only purchase 5,12,24,36 meals.
回答1:
function checkout_validate() {
// Only run in the Cart or Checkout pages
if( is_cart() || is_checkout() ) {
// Get number of items in the cart.
$items_in_cart = WC()->cart->get_cart_contents_count();
// Allowed amounts
$allowed_amounts = array(5, 12, 24, 36);
// If items in cart NOT equal to allowed amounts, show error message
if ( !in_array( $items_in_cart, $allowed_amounts)) {
wc_add_notice( __( 'Remember that you can only buy 5, 12, 24 or 36 meals. You have ' . $items_in_cart . ' maeals in your cart.', 'woocommerce' ), 'error' );
remove_action( 'woocommerce_proceed_to_checkout', 'woocommerce_button_proceed_to_checkout', 20 );
}
}
}
add_action( 'woocommerce_check_cart_items' , 'checkout_validate' );
来源:https://stackoverflow.com/questions/60238522/force-to-buy-only-predefined-quantities-at-checkout-in-woocommerce