我通过连接到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);
}
}
}
费用显示在购物车页面上,但不会保留在 checkout 和订购页面上.
我试过用$cart->set_session()
,但没有效果.
更新:我已经创建了一个新的可湿性粉剂网站与一个空白的主题(白板),只有最新版本的WooCommerce安装,我仍然得到错误.