我在WooCommerce中使用WooCommerce订阅插件。我正在尝试编写一个功能,当 满足以下条件时,对正常产品执行10%折扣:
function vip_discount() {
$woocommerce = WC();
$items = $woocommerce->cart->get_cart();
$vip_product_id = get_subscription_product_id();
$is_vip_in_cart = is_in_cart($vip_product_id);
$vip_product_price = 0;
foreach ($items as $item) {
if( $item['variation_id'] === get_subscription_variation_id('monthly') || $item['variation_id'] === get_subscription_variation_id('quarterly') || $item['variation_id'] === get_subscription_variation_id('annually') ) {
$vip_product_price = $item['line_total'];
}
}
if ( wcs_user_has_subscription( '', '', 'active' ) || $is_vip_in_cart ) {
// Make sure that the calculation is a negative number at the end ALWAYS!
$discount = -( 10 / 100 ) * ( $woocommerce->cart->get_displayed_subtotal() - $vip_product_price);
print_r($discount);
$woocommerce->cart->add_fee( 'VIP Discount', $discount );
}
}
add_action( 'woocommerce_cart_calculate_fees', 'vip_discount' );
问题是这个钩子出于某种原因运行了两次。它也没有应用正确的费用。它应该从负面应用的费用中减去经常性项目总额,而不是费用最终作为订阅(经常性)产品价格本身。
感谢任何补充信息或帮助。
答案 0 :(得分:0)
首先,如果您使用$woocommerce
,首先需要global $woocommerce;
。最好使用WC()
作为同一事物的实际方式。
使用woocommerce_cart_calculate_fees
操作挂钩,您的挂钩函数中缺少参数$cart
(WC_Cart
对象)。
函数get_subscription_product_id()
不会退出,因此它可能是一个自定义函数...我已用其他东西替换它。
您应该使用cart_contents_total
而不是显示的小计,因为此挂钩在总计算之前运行。
请尝试重新访问类似代码:
add_action( 'woocommerce_cart_calculate_fees', 'vip_discount', 10, 1 );
function vip_discount( $cart ) {
if ( is_admin() && ! defined('DOING_AJAX') ) return; // Exit
// Here the rate percentage of 10% to be applied
$rate = .10;
// Initializing variables
$vip_price = $discount = 0;
$subscription_in_cart = false;
// Loop through the cart items
foreach ($cart->get_cart() as $cart_item) {
if( $cart_item['variation_id'] === get_subscription_variation_id('monthly') || $cart_item['variation_id'] === get_subscription_variation_id('quarterly') || $cart_item['variation_id'] === get_subscription_variation_id('annually') ) {
$vip_price += $cart_item['line_total'];
}
// Get an instance of the parent product object (if not parent the product object)
$product = wc_get_product( $cart_item['product_id']);
// Check for simple or variable "subscription" products
if( $product->is_type('subscription') || $product->is_type('variable-subscription') ){
$subscription_in_cart = true;
}
}
// If customer has an active subscription or a product subscription in cart
if ( wcs_user_has_subscription( '', '', 'active' ) || $subscription_in_cart ) {
// The discount calculation
$discount = ( $cart->cart_contents_total - $vip_product_price ) * $rate;
if( $discount > 0 ){
// Add a negative fee (a discount)
$cart->add_fee( __("VIP Discount"), -$discount ); // not taxable here
}
}
}
此代码位于活动子主题(或主题)的function.php文件中或任何插件文件中。
这应该有效。