doushi2047 2018-04-06 13:08
浏览 62
已采纳

在Woocommerce中降低成本的产品的购物车折扣

How can I apply a discount in products cart for product that costs less?

For example:
I have two product in cart: one cost 150$ and one 200$. I would like to apply a 10 percent discount only for product that cost less, in this case the first one.

I have this code but it works only for the second product in cart:

add_filter( 'woocommerce_before_calculate_totals', 'discount_on_2nd_cart_item', 10, 1 );
function discount_on_2nd_cart_item( $cart_object ) {

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

    // Initialising
    $count = 0;
    $discount = 0.10; // 10 %
    $discounted = 0;
    // Iterating though each cart items
    foreach ( $cart_object->get_cart() as $cart_item ) {
        $count++;
        if( 2 == $count){ // Second item only
            $price = $cart_item['data']->get_price(); // product price
            $discounted_price = $price - ($price * $discount); // calculation
            $discounted = $price - $discounted_price;
            // Set the new price
            //$cart_item['data']->set_price( $discounted_price );
            break; // stop the loop
        }
    }

    $cart_object->add_fee( "Discount (10%) on second product", -$discounted, true );
}
  • 写回答

1条回答 默认 最新

  • douxin8749 2018-04-06 17:46
    关注

    For Cart fees, you should use woocommerce_cart_calculate_fees dedicated hook instead this way:

    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;
    
        // Only for 2 items or more
        if ( $cart->get_cart_contents_count() < 2 ) return;
    
        // Initialising
        $percentage = 10; // 10 %
        $discount = 0;
        $item_prices = array();
    
        // Loop though each cart items and set prices in an array
        foreach ( $cart->get_cart() as $cart_item ) {
            $product_prices_excl_tax[] = wc_get_price_excluding_tax( $cart_item['data'] );
        }
        sort($product_prices_excl_tax);
    
        $discount = reset($product_prices_excl_tax) * $percentage / 100;
    
        $cart->add_fee( "Discount on cheapest (".$percentage."%)", -$discount );
    }
    

    Code goes in function.php file of your active child theme (or active theme). Tested and works.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 angular开发过程中,想要读取模型文件,即图1的335行,会报404错误(如图2)。但我的springboot里配置了静态资源文件,如图3。且在该地址下我有模型文件如图4,请问该问题该如何解决呢?
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了
  • ¥100 H5网页如何调用微信扫一扫功能?
  • ¥15 讲解电路图,付费求解
  • ¥15 有偿请教计算电磁学的问题涉及到空间中时域UTD和FDTD算法结合的
  • ¥15 vite打包后,页面出现h.createElement is not a function,但本地运行正常
  • ¥15 Java,消息推送配置