我希望客户购物车中的产品数量是6或12或4的倍数。我在论坛中找到了乘法器6的代码,但它需要为其他系数进行编辑。
基于Set item quantity to multiples of “x” for products in a specific category in Woocommerce代码线程:
// check that cart items quantities totals are in multiples of 6
add_action( 'woocommerce_check_cart_items', 'woocommerce_check_cart_quantities' );
function woocommerce_check_cart_quantities() {
$multiples = 6;
$total_products = 0;
foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
$total_products += $values['quantity'];
}
if ( ( $total_products % $multiples ) > 0 )
wc_add_notice( sprintf( __('You need to buy in quantities of %s products', 'woocommerce'), $multiples ), 'error' );
}基于Woocommerce Order Quantity in Multiples答案代码:
// Limit cart items with a certain shipping class to be purchased in multiple only
add_action( 'woocommerce_check_cart_items', 'woocommerce_check_cart_quantities_for_class' );
function woocommerce_check_cart_quantities_for_class() {
$multiples = 6;
$class = 'bottle';
$total_products = 0;
foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
$product = get_product( $values['product_id'] );
if ( $product->get_shipping_class() == $class ) {
$total_products += $values['quantity'];
}
}
if ( ( $total_products % $multiples ) > 0 )
wc_add_notice( sprintf( __('You need to purchase bottles in quantities of %s', 'woocommerce'), $multiples ), 'error' );
} 如何处理6或12或4的倍数而不是一倍?
发布于 2020-10-25 19:28:19
由于12已经是4或6的倍数,所以只需使用以下代码(注释)检查项目倍数为4或6的项。
add_action( 'woocommerce_check_cart_items', 'check_cart_items_quantities_conditionally' );
function check_cart_items_quantities_conditionally() {
$multiples = array(4, 6); // Your defined multiples in an array
$items_count = WC()->cart->get_cart_contents_count(); // Get total items cumulated quantity
$is_multiple = false; // initializing
// Loop through defined multiples
foreach ( $multiples as $multiple ) {
if ( ( $items_count % $multiple ) == 0 ) {
$is_multiple = true; // When a multiple is found, flag it as true
break; // Stop the loop
}
}
// If total items cumulated quantity doesn't match with any multiple
if ( ! $is_multiple ) {
// Display a notice avoiding checkout
wc_add_notice( sprintf( __('You need to buy in quantities of %s products', 'woocommerce'), implode(' or ', $multiples) ), 'error' );
}
}https://stackoverflow.com/questions/64526023
复制相似问题