繁体   English   中英

"基于数量计算的产品类别的购物车折扣"

[英]Cart discount for a product category based on quantity calculations

我想向 woocommerce 添加一个函数,当将一个类别的 12-23 件商品添加到购物车时,该函数将计算 10% 的折扣。

然后,如果添加该类别的 24 - 47 个项目,则将获得 15% 的折扣。

最后,如果添加此类别的 48 件以上商品,则可享受 20% 的折扣。

实际的代码示例会很棒,因为我是 woocommerce 的新手

更新-更正了代码错误并在输出的折扣文本中添加了增强功能

这是在woocommerce_cart_calculate_fees挂钩中挂钩的函数, woocommerce_cart_calculate_fees根据购物车项目数量计算为该特定类别(或子类别)提供折扣。

这是代码:

add_action( 'woocommerce_cart_calculate_fees', 'cart_items_quantity_wine_discount', 10, 1 );
function cart_items_quantity_wine_discount($cart_object) {

    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    // Set HERE your category (can be an ID, a slug or the name)
    $category = 34; // or a slug: $category = 'wine';

    $category_count = 0;
    $category_total = 0;
    $discount = 0;

    // Iterating through each cart item
    foreach($cart_object->get_cart() as $cart_item):

        if( has_term( $category, 'product_cat', $cart_item['product_id']) ):
            $category_count += $cart_item['quantity'];
            $category_total += $cart_item["line_total"]; // calculated total items amount (quantity x price)
        endif;

    endforeach;

    $discount_text = __( 'Quantity discount of ', 'woocommerce' );

    // ## CALCULATIONS ##
    if ( $category_count >= 12 && $category_count < 24 ) {
        $discount -= $category_total * 0.1; // Discount of 10% 
        $discount_text_output = $discount_text . '10%';
    } elseif ( $category_count >= 24 && $category_count < 48 ) {
        $discount -= $category_total * 0.15; // Discount of 15%
        $discount_text_output = $discount_text . '15%';
    } elseif ( $category_count >= 48 ) {
        $discount -= $category_total * 0.2; // Discount of 20%
        $discount_text_output = $discount_text . '20%';
    }

    // Adding the discount
    if ( $discount != 0 && $category_count >= 12 )
        $cart_object->add_fee( $discount_text_output, $discount, false );

    // Note: Last argument in add_fee() method is related to applying the tax or not to the discount (true or false)
}

注意: add_fee()方法中的最后一个参数与是否将税收应用于折扣有关……

代码经过测试且功能齐全。

代码位于活动子主题(或主题)的 function.php 文件中。 或者也可以在任何插件 php 文件中。


其他类似: 基于产品总数的某些类别的折扣

@LoicTheAztec,

如果我们想使用或添加多个类别,您能否建议更新的代码。 根据上面的代码,我认为一次只能添加 1 个类别你能分享代码问候吗

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM