首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在WooCommerce中将购物车总量限制在特定倍数上

在WooCommerce中将购物车总量限制在特定倍数上
EN

Stack Overflow用户
提问于 2020-10-25 16:23:38
回答 1查看 277关注 0票数 2

我希望客户购物车中的产品数量是6或12或4的倍数。我在论坛中找到了乘法器6的代码,但它需要为其他系数进行编辑。

基于Set item quantity to multiples of “x” for products in a specific category in Woocommerce代码线程:

代码语言:javascript
复制
// 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答案代码:

代码语言:javascript
复制
// 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的倍数而不是一倍?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-10-25 19:28:19

由于12已经是4或6的倍数,所以只需使用以下代码(注释)检查项目倍数为4或6的项。

代码语言:javascript
复制
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' );
    }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64526023

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档