我通过挂钩
woocommerce_cart_calculate_fees
操作向购物车添加自定义费用,如下所示:
if (isset($_GET['discount'])) {
add_action('woocommerce_cart_calculate_fees', 'add_loyalty_discounts');
}
function add_loyalty_discounts(WC_Cart $cart)
{
$total = 0;
global $woocommerce;
foreach (WC()->cart->get_cart() as $cart_item_key => $item) {
$total += $item['data']->regular_price;
$woocommerce->cart->cart_contents[$cart_item_key]['discount_amount'] = $_GET['discount'];
}
if ($total < $_GET['discount']) {
wc_add_notice('You must spend more than €' . $_GET['discount'] . ' to use your loyalty discount.', 'error');
} else {
$current_user = wp_get_current_user();
$loyalty_points = empty(get_user_meta($current_user->ID, 'loyalty_points', true)) ? 0 : get_user_meta($current_user->ID, 'loyalty_points', true);
$loyalty_points = 100;
if ($loyalty_points < $_GET['discount']) {
wc_add_notice('You do not have enough loyalty points to apply this discount.', 'error');
} else {
$cart->add_fee('Loyalty Discount', -intval($_GET['discount']), true);
}
}
}
费用显示在购物车页面上,但不会保留在结账和订单页面上。
我尝试过使用
$cart->set_session()
但这没有效果。
更新:我创建了一个带有空白主题 (blankslate) 的新 WP 网站,并且仅安装了最新版本的 WooCommerce,但我仍然收到错误。
您的代码中存在一些错误和遗漏的内容,请尝试以下操作:
add_action('woocommerce_cart_calculate_fees', 'add_loyalty_discounts');
function add_loyalty_discounts($cart) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
$cart->add_fee('Loyalty Discount', -intval(100), true);
}
代码位于子主题的 function.php 文件中(或插件中)。现在应该可以工作了。
相关:
我测试过,它在购物车和结账页面上都运行良好
function add_loyalty_discounts(WC_Cart $cart) {
$cart->add_fee('Loyalty Discount', -intval(100), true);
}
add_action('woocommerce_cart_calculate_fees', 'add_loyalty_discounts');