基于商品数量计数的WooCommerce购物车中的折扣

时间:2020-06-18 00:12:00

标签: php wordpress woocommerce hook-woocommerce taxonomy-terms

我有一类产品的价格都在15美元以下。当用户从此类别中购买10到20种产品时,他们应获得10美元的折扣价。当用户购买20+后,价格再次变为$ 5。用户不能分配自定义角色(例如批发商)。我根据另一个问题的LoicTheAztec代码松散地创建了代码,并添加了自己的修改和代码。看起来应该可以使用。我没有收到任何错误,但无法正常工作。

add_action('woocommerce_before_cart', 'check_product_category_in_cart');

function check_product_category_in_cart() {
    // HERE set your product categories in the array (can be IDs, slugs or names)
    $categories = array('surfacing-adhesives');
    $found      = false; // Initializing

    $count = 0;

    // Loop through cart items      
    foreach ( WC()->cart->get_cart() as $cart_item ) {
        // If product categories is found
        if ( has_term( $categories, 'product_cat', $cart_item['product_id'] ) ) {
            $count++;
        }
    }

    if (!current_user_can('wholesaler')) {
        // Discounts
        if ($count > 10 && $count < 20) {
            // Drop the per item price
            $price = 10;
        } else if ($count > 20) {
            // Drop the per item price
            $price = 5;
        } else {
            // Did not qualify for volume discount
        }
    }
}

1 个答案:

答案 0 :(得分:1)

您使用的钩子不正确,并且缺少一些东西。请尝试以下操作:

add_action( 'woocommerce_before_calculate_totals', 'discounted_cart_item_price', 20, 1 );
function discounted_cart_item_price( $cart ){
    // Not for wholesaler user role
    if ( ( is_admin() && ! defined( 'DOING_AJAX' ) ) || current_user_can('wholesaler') )
        return;

    // Required since Woocommerce version 3.2 for cart items properties changes
    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
        return;

    // HERE set your product categories in the array (can be IDs, slugs or names)
    $categories = array('surfacing-adhesives');
    $categories = array('t-shirts');

    // Initializing
    $found = false;
    $count = 0;

    // 1st Loop: get category items count  
    foreach ( WC()->cart->get_cart() as $cart_item ) {
        // If product categories is found
        if ( has_term( $categories, 'product_cat', $cart_item['product_id'] ) ) {
            $count += $cart_item['quantity'];
        }
    }

    // Applying discount
    if ( $count >= 10 ) {
        // Discount calculation (Drop the per item qty price)
        $price = $count >= 20 ? 5 : 10;

        // 2nd Loop: Set discounted price  
        foreach ( WC()->cart->get_cart() as $cart_item ) {
            // If product categories is found
            if ( has_term( $categories, 'product_cat', $cart_item['product_id'] ) ) {
                $cart_item['data']->set_price( $price );
            }
        }
    }
}

代码进入活动子主题(或活动主题)的functions.php文件中。经过测试,可以正常工作。