【问题标题】:Set item quantity to multiples of “x” for products in a specific category in Woocommerce在 Woocommerce 中将特定类别中的产品的项目数量设置为“x”的倍数
【发布时间】:2018-10-02 16:21:30
【问题描述】:

我在网上找到了一个 sn-p,它允许您在购物车中设置最低购买数量为多个“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' );
}

我希望此规则仅对属于特定类别的产品有效,“id = 35”。

其他类别的所有产品也可以少量购买。

【问题讨论】:

    标签: php wordpress woocommerce cart custom-taxonomy


    【解决方案1】:

    更新 (也扩展到父产品类别)

    尝试以下方法,让您的代码仅适用于特定产品类别:

    // Custom conditional function that checks also for parent product categories
    function has_product_category( $product_id, $category_ids ) {
        $term_ids = array(); // Initializing
    
        // Loop through the current product category terms to get only parent main category term
        foreach( get_the_terms( $product_id, 'product_cat' ) as $term ){
            if( $term->parent > 0 ){
                $term_ids[] = $term->parent; // Set the parent product category
                $term_ids[] = $term->term_id;
            } else {
                $term_ids[] = $term->term_id;
            }
        }
        return array_intersect( $category_ids, array_unique($term_ids) );
    }
    
    
    add_action( 'woocommerce_check_cart_items', 'woocommerce_check_cart_quantities' );
    function woocommerce_check_cart_quantities() {
        $multiples = 6;
        $total_products = 0;
        $category_ids = array( 35 );
        $found = false;
    
        foreach ( WC()->cart->get_cart() as $cart_item ) {
            if ( has_product_category( $cart_item['product_id'], $category_ids ) ) {
                $total_products += $cart_item['quantity'];
                $found = true;
            }
        }
        if ( ( $total_products % $multiples ) > 0 && $found )
            wc_add_notice( sprintf( __('You need to buy in quantities of %s products', 'woocommerce'), $multiples ), 'error' );
    }
    

    代码进入您的活动子主题(活动主题)的 function.php 文件中。经过测试并且可以工作。

    【讨论】:

    • 不幸的是它不起作用。详细说明:它使我可以输入任何数量的属于“35”类别的产品,而不会显示错误消息。
    • @Vdga​​etano 已更新 - 我刚刚测试了我的代码,它完全适用于定义的产品类别(但不适用于父产品类别)。所以现在我更新了我的答案代码来处理父产品类别。请再试一次。
    猜你喜欢
    • 1970-01-01
    • 2021-05-08
    • 1970-01-01
    • 2020-09-18
    • 1970-01-01
    • 1970-01-01
    • 2018-01-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多