gpt4 book ai didi

php - 根据 WooCommerce 中的总额自动应用百分比或固定购物车折扣

转载 作者:行者123 更新时间:2023-12-02 20:32:28 25 4
gpt4 key购买 nike

我正在尝试在客户的 WooCommerce 网站上设置优惠券,以便在购物车总数低于上限金额或固定金额等于或大于上限金额时应用百分比折扣。

假设购物车总数的上限为 200。如果购物车总数低于此上限,则应用 10% 的折扣。但如果购物车总数为 200 件或更多,则固定金额 20 件将用作折扣。

例如:

  • 我的购物车总数为 190 件。由于这低于上限 200 件,因此折扣金额按 10% 计算,即应用 19
  • 我的购物车总数为 210 件。由于这大于上限 200 件,因此应用固定数量 20 件。

如何将我的 WooCommerce 设置为根据总额应用百分比折扣或固定购物车?

最佳答案

您可以使用 Hook 在 woocommerce_before_calculate_totals 操作 Hook 中的自定义函数,您将在其中定义 2 个优惠券代码:

  • 百分比折扣优惠券代码(10%)
  • 固定金额折扣优惠券代码(20 美元)

代码:

add_action( 'woocommerce_before_calculate_totals', 'auto_add_coupons_total_based', 10, 1 );
function auto_add_coupons_total_based( $cart ) {

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

if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;

// HERE define your coupon code
$coupon_percent = 'uget10percent'; # <=== <=== <=== <=== <=== <===
$coupon_fixed = 'uget20off'; # <=== <=== <=== <=== <=== <=== <===

// Get cart subtotal
$subtotal = 0;
foreach($cart->get_cart() as $cart_item ){
$subtotal += $cart_item['line_subtotal'];
$subtotal += $cart_item['line_subtotal_tax']; // with taxes
}

// Coupon type "percent" (less than 200)
if( $subtotal < 200 && ! $cart->has_discount( $coupon_percent ) ){
// If coupon "fixed amount" type is in cart we remove it
if( $cart->has_discount( $coupon_fixed ) )
$cart->remove_coupon( $coupon_fixed );

// Apply the "percent" type coupon code
$cart->add_discount( $coupon_percent );
}
// Coupon type "fixed amount" (Up to 200)
elseif( $subtotal >= 200 && ! $cart->has_discount( $coupon_fixed ) ) {
// If coupon "percent" type is in cart we remove it
if( $cart->has_discount( $coupon_percent ) )
$cart->remove_coupon( $coupon_percent );

// Apply the "fixed amount" type coupon code
$cart->add_discount( $coupon_fixed );
}
}

代码位于事件子主题(或事件主题)的 function.php 文件中。

经过测试并有效。

If you want to apply it on subtotal without taxes you will have to comment this line:

$subtotal += $cart_item['line_subtotal_tax']; // with taxes

或者您也可以使用负费用(即折扣)来代替优惠券:

add_action( 'woocommerce_cart_calculate_fees', 'discount_based_on_total', 25, 1 );
function discount_based_on_total( $cart ) {

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

$total = $cart->cart_contents_total;

// Percentage discount (10%)
if( $total < 200 )
$discount = $total * 0.1;
// Fixed amount discount ($20)
else
$discount = 20;

// Add the discount
$cart->add_fee( __('discount', 'woocommerce'), -$discount );
}

代码位于事件子主题(或事件主题)的 function.php 文件中。

经过测试并有效。

关于php - 根据 WooCommerce 中的总额自动应用百分比或固定购物车折扣,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48265179/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com