【发布时间】:2018-08-28 11:16:13
【问题描述】:
我在我的 functions.php 中使用此代码对我的产品应用 10% 的折扣,从购物车中的第二个开始:
function add_discount_price_percent( $cart_object ) {
global $woocommerce;
$pdtcnt=0;
foreach ($woocommerce->cart->get_cart() as $cart_item_key => $cart_item) {
$pdtcnt++;
$oldprice = 0;
$newprice = 0;
if($pdtcnt>1) { // from second product
$oldprice = $cart_item['data']->price; //original product price
// echo "$oldprice<br />";
$newprice = $oldprice*0.9; //discounted price
$cart_item['data']->set_sale_price($newprice);
$cart_item['data']->set_price($newprice);
$cart_item['data']->set_regular_price($oldprice);
}
}
WC()->cart->calculate_totals();
}
add_action( 'woocommerce_before_cart', 'add_discount_price_percent', 1);
add_action( 'woocommerce_before_checkout_form', 'add_discount_price_percent', 99 );
价格在购物车和结帐页面中都正确显示,但是当我使用 PayPal 沙盒测试我的付款时,我看到并且必须支付全价,因为折扣被忽略了。
如果我在提交按钮之前回显折扣价格,我会得到正确的价格:
function echo_discount_before_checkout_submit() {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
foreach ( WC()->cart->get_cart() as $key => $value ) {
echo $value['data']->price . "<br />";
}
}
add_action( 'woocommerce_review_order_before_submit', 'echo_discount_before_checkout_submit', 99 );
如何向 PayPal 发送正确的折扣价格?
编辑:@LoisTheAtzec 的回复非常好,但如果数量超过 2,即使是第一个产品,我也需要 10% 的折扣:我正在尝试此代码,但我无法获得正确的值。
// If it is the first product and quantity is over 1
if ($count === 1 && $cart_item['quantity'] >= 2) {
// get unit price
$unit_price = $cart_item['data']->get_price();
// get quantity to discount (total - 1)
$discounted_quantity = $cart_item['quantity'] - 1;
// get total discount amount (on total quantity - 1)
$discounted_amount = ($unit_price * $discounted_quantity) * 0.9;
// add first non discounted price to total discount amount
$total_discounted_price = $unit_price + $discounted_amount;
// distribute discount over total quantity and get new unit price
$distributed_unit_discount = $total_discounted_price / $cart_item['quantity'];
// set new unit price
$cart_item['data']->set_price($distributed_unit_discount);
}
2018 年 9 月 6 日更新
我在登录用户时遇到了一个奇怪的行为,可能取决于插件之间的一些冲突或我使用的主题 (Avada):折扣应用了两次,所以我不得不阻止此代码添加到我的函数中:
// Set the discounted price on 2nd item and
add_action('woocommerce_before_calculate_totals', 'add_discount_percentage_on_2nd_item', 999, 1);
function add_discount_percentage_on_2nd_item($cart) {
if (is_admin() && !defined('DOING_AJAX'))
return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
希望对你有帮助。
【问题讨论】:
标签: wordpress woocommerce checkout orders discount