在没有优惠券的情况下在 WooCommerce 中设置折扣 [英] Set a discount in WooCommerce without a coupon

查看:24
本文介绍了在没有优惠券的情况下在 WooCommerce 中设置折扣的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要手动设置折扣而不使用优惠券.

我查看了 Github 中的 Woocommerce 源代码,发现它使用了set_discount_total"函数,但它不起作用.

我尝试过 WC()->cart->set_discount_total(15)$order->set_discount_total(15); 但什么都没有.>

这是我的代码:

set_discount_total(50);}add_action('woocommerce_checkout_order_processed','letsgo_order_total',10,3);?>

实际上我发现了一种方法,它有效,但我不喜欢代码:

解决方案

这是我使用过并且运行良好的这个答案的代码片段.如何为购物车总额添加折扣?

//计算费用前钩子add_action('woocommerce_cart_calculate_fees', 'add_custom_fees');/*** 如果超过三件,加收定制费* @param WC_Cart $cart*/函数 add_custom_fees( WC_Cart $cart ){if( $cart->cart_contents_count <3 ){返回;}//计算要减少的数量$discount = $cart-> 小计 * 0.1;$cart->add_fee( '您的购物车中的商品超过 3 件,已添加 10% 的折扣.', -$discount);}

I need set a discount manually without using coupons.

I have checked the Woocommerce source in Github and I see that it uses "set_discount_total" functions, but it does not work.

I have tried WC()->cart->set_discount_total(15) and $order->set_discount_total(15); but nothing.

This is my code:

<?php
function letsgo_order_total($order_id, $posted_data, $order) {
    $order = wc_get_order( $order_id );
    $order->set_discount_total(50);
}
add_action('woocommerce_checkout_order_processed','letsgo_order_total',10,3);
?>

Actually I have discovered a way to do it, it works but I do not like the code:

<?php
$cart_discount = 50;
$discount = (double)get_post_meta($order_id,'_cart_discount',true);
update_post_meta($order_id,'_cart_discount',$cart_discount + $discount);
?>

解决方案

This is a code snippet from this answer which I have used and works well. How to add discount to cart total?

 // Hook before calculate fees
add_action('woocommerce_cart_calculate_fees' , 'add_custom_fees');

/**
 * Add custom fee if more than three article
 * @param WC_Cart $cart
 */
function add_custom_fees( WC_Cart $cart ){
    if( $cart->cart_contents_count < 3 ){
        return;
    }

    // Calculate the amount to reduce
    $discount = $cart->subtotal * 0.1;
    $cart->add_fee( 'You have more than 3 items in your cart, a 10% discount has been added.', -$discount);
}

这篇关于在没有优惠券的情况下在 WooCommerce 中设置折扣的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆