商品IDと数量条件に基づいてWooCommerceストアにクーポンを自動的に適用しようとしています。私の最終目標は、所望の製品のうちの2つがカートに追加されたときに、特定のクーポンが自動的に適用され、所望の製品の3つがカートに追加されるときに自動的に別のクーポンが自動的に適用されることである。製品の単一の数量には割引がありません。 次は今を動作するコードの修正版である:私はあなたの関数でeverithing書き換えている ...特定の製品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