【问题标题】:Discounting the cheapest item for a specific category in WooCommerce在 WooCommerce 中为特定类别打折最便宜的商品
【发布时间】:2019-09-16 21:42:15
【问题描述】:

我很想根据产品类别打折 Woocommerce 中最便宜的购物车商品。基于 "Cart discount for product that cost less in Woocommerce" 完美运行的答案代码。

但是如何让它只适用于特定的产品类别。

我们的想法是在购物车中有 2 件产品,并为特定产品类别的最便宜商品提供折扣。

【问题讨论】:

    标签: php wordpress woocommerce cart discount


    【解决方案1】:

    更新 - 限定产品类别中的 2 件商品。

    以下将对特定的产品类别(在代码中定义)执行相同的操作:

    add_action('woocommerce_cart_calculate_fees', 'discount_on_cheapest_cart_item', 20, 1 );
    function discount_on_cheapest_cart_item( $cart ) {
        if ( is_admin() && ! defined( 'DOING_AJAX' ) )
            return;
    
        // Settings
        $categories = ['tshirts']; // Your product categories (coma separated)
        $percentage = 10; // 10 % discount
    
        // Only for 2 items or more
        if ( $cart->get_cart_contents_count() < 2 ) return;
    
        // Initialising
        $discount = 0;
        $item_prices = array();
    
        // Loop though each cart items and set prices in an array
        foreach ( $cart->get_cart() as $cart_item ) {
            if( has_term( $categories, 'product_cat', $cart_item['product_id'] ) ) {
                $product_prices_excl_tax[] = wc_get_price_excluding_tax( $cart_item['data'] );
            }
        }
    
        // We set the fee for 2 items of the defined product category
        if( count($product_prices_excl_tax) == 2 ) {
    
            sort($product_prices_excl_tax);
    
            $discount = reset($product_prices_excl_tax) * $percentage / 100;
    
            $cart->add_fee( sprintf( __("Discount on cheapest %s"), '('.$percentage.'%)' ), -$discount );
        }
    }
    

    代码进入您的活动子主题(或活动主题)的 function.php 文件中。它应该可以工作。

    【讨论】:

    • 谢谢,我有一个问题,你有可能只有当你有(2)个产品,如果你添加超过 2 个产品不再服务?非常感谢,一直在关注你的工作,做一些教程解释吗? @LoicTheAztec
    • 你知道我该怎么做吗? @LoicTheAztec
    • 准备好了,并按照文章所述接受了他的回复。他再次重申了我的赞赏。 @LoicTheAztec
    • @AlvaroMejia 更新了……看看是不是你想要的。
    • 你好朋友,看我正在测试你的代码,我的商店所有类别都获得了折扣。你知道为什么吗?,即使我不明白为什么它只在你想要的类别中有效。 @LoicTheAztec
    猜你喜欢
    • 1970-01-01
    • 2020-08-12
    • 1970-01-01
    • 2019-09-18
    • 1970-01-01
    • 1970-01-01
    • 2021-06-01
    • 1970-01-01
    • 2019-01-26
    相关资源
    最近更新 更多