我試圖根據產品ID和數量條件自動在我的WooCommerce商店中應用優惠券。我的最終目標是在將兩(2)個所需產品添加到購物車時自動應用特定優惠券,並在購買三(3)個所需產品時自動應用其他優惠券。單一數量的產品應該沒有折扣。 以下是代碼,現在該功能修正版本:自動爲特定產品ID和數量自動應用優惠券
add_action('woocommerce_before_cart', 'conditional_auto_add_coupons');
function conditional_auto_add_coupons() {
if (!WC()->cart->is_empty()){
// Define HERE your Targeted Product ID and coupons codes
$target_pid = 103;
$coupon1 = 'soccer-sibling-2';
$coupon2 = 'soccer-sibling-3';
// First cart loop: Counting number of subactegory items in cart
foreach (WC()->cart->get_cart() as $cart_item){
if($target_pid == $cart_item['data']->id){
// Removes any coupons in the cart already
WC()->cart->remove_coupons();
if(2 == WC()->cart->get_cart_contents_count() && !WC()->cart->has_discount($coupon1)){
WC()->cart->remove_coupons();
WC()->cart->add_discount($coupon1);
wc_add_notice(__('The multiple sibling discount has been applied.', 'theme_domain'), 'success');
} elseif(3 == WC()->cart->get_cart_contents_count() && !WC()->cart->has_discount($coupon2)){
WC()->cart->remove_coupons();
WC()->cart->add_discount($coupon2);
wc_add_notice(__('The multiple sibling discount has been applied.', 'theme_domain'), 'success');
}
// Recalculates Cart Totals to show correct price
WC()->cart->calculate_totals();
}
}
}
}
你得到了什麼錯誤信息? –
嗯,我注意到我的粘貼代碼中有一個語法錯誤。糾正了這一點。我調試時得到的錯誤是「注意:嘗試在333行上的/home/...functions.php中獲取非對象的屬性」。有問題的線條是'if($ _product-> id == $ product_id)' – GDailey