gpt4 book ai didi

php - WooCommerce:带优惠券的促销产品双倍折扣

转载 作者:行者123 更新时间:2023-12-05 04:41:29 26 4
gpt4 key购买 nike

我想使用优惠券代码对促销产品进行双倍折扣。

例如:产品以 10% 的折扣促销。如果我添加优惠券代码 doublediscount 我想将该折扣加倍至 20%。

优惠券折扣应有 15% 的限制。因此,如果产品以 30% 的折扣打折,则使用优惠券代码的最大附加折扣应为 15%。导致正常价格的 45% 折扣(促销 + 额外折扣)。

到目前为止我的代码是这样的:

add_action( 'woocommerce_before_calculate_totals', 'double_saleprice_coupon' );
function double_saleprice_coupon( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;

global $woocommerce;
$coupon_id = 'doublediscount';

// Loop through cart items (first loop)
foreach ( $cart->get_cart() as $cart_item_key => $cart_item ){

// Check if product in cart is on sale
$product = $cart_item['data'];
$cart_item_regular_price = $cart_item['data']->get_regular_price();
$cart_item_sale_price = $cart_item['data']->get_sale_price();
$cart_item_diff = $cart_item_regular_price - $cart_item_sale_price;
$cart_item_per_cent = round( $cart_item_diff / $cart_item_regular_price * 100, 0 );

if ( $product->is_on_sale() && wc_pb_is_bundled_cart_item($cart_item) === false && $cart_item_per_cent < 15 ) {
echo 'on sale';
echo $cart_item_per_cent;
}

}
}

我遍历所有购物车商品并检查它们是否在打折以及折扣是否低于 15%。如果是这样,我想更改这些购物车商品的折扣。

如果购物车商品的折扣超过 15%,我什么都不想做。因此,优惠券代码 doublediscount 将对他们应用 15%。

我只是不知道如何添加/更改购物车商品的折扣。

最佳答案

您可以结合以下优惠券设置使用 woocommerce_coupon_get_discount_amount Hook :

  • 正确设置您的优惠券代码:doublediscount
  • 折扣类型:百分比
  • 金额:15

此答案中应用的步骤:

  • 仅当特定的优惠券代码匹配并且产品正在销售时
  • 如果产品未打折,则不会应用折扣(else 条件等于 0。但是,如果这不适用,您可以简单地删除 else条件)
  • 计算促销产品的当前折扣百分比。如果这小于最大附加折扣 (15),然后折扣翻倍
  • 如果大于此,将自动应用添加的最大折扣 (15)

所以你得到:

function filter_woocommerce_coupon_get_discount_amount( $discount, $price_to_discount , $cart_item, $single, $coupon ) {
// Returns true when viewing the cart page & only apply for this coupon
if ( is_cart() || is_checkout() && $coupon->get_code() == 'doublediscount' ) {
// Get an instance of the WC_Product object
$product = $cart_item['data'];

// Is a WC product
if ( is_a( $product, 'WC_Product' ) ) {
// On sale
if ( $product->is_on_sale() ) {
// Regular price
$cart_item_regular_price = $product->get_regular_price();

// Sale price
$cart_item_sale_price = $product->get_sale_price();

// Calculate the percentage difference
$cart_item_diff = $cart_item_regular_price - $cart_item_sale_price;
$cart_item_percentage = round( $cart_item_diff / $cart_item_regular_price * 100, 0 );

// Get maximum added discount
$max_added_discount = $coupon->get_amount();

// Less than maximum added discount
if ( $cart_item_percentage < $max_added_discount ) {
$discount = round( ( $price_to_discount * $cart_item_percentage ) / 100, 0 );
}
} else {
$discount = 0;
}
}
}

return $discount;
}
add_filter( 'woocommerce_coupon_get_discount_amount', 'filter_woocommerce_coupon_get_discount_amount', 10, 5 );

关于php - WooCommerce:带优惠券的促销产品双倍折扣,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70063577/

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