我期待使用woocommerce智能優惠券創建「邀請代碼」。爲此,我希望特定產品在購物車/結帳時要求使用優惠券代碼。我已經看到了這樣做的方法,但它們會影響所有產品,而不僅僅是我想要的產品。顯示具有特定產品類別的強制性優惠券代碼的通知
我想將返回的變量傳遞給另一個函數,但我不知道如何去做。
以下是最新版本:
//Check to see if user has product with a specific product category in cart
function check_product_in_cart() {
global $woocommerce;
//assigns a default negative value
// categories targeted 87, 18, 19
$product_in_cart = false;
// start of the loop that fetches the cart items
foreach ($woocommerce->cart->get_cart() as $cart_item_key => $values) {
$_product = $values['data'];
$terms = get_the_terms($_product->id, 'product_cat');
// second level loop search, in case some items have several categories
foreach ($terms as $term) {
$_categoryid = $term->term_id;
if (($_categoryid === 87) || ($_categoryid === 18) || ($_categoryid === 19)) {
//category is in cart!
$product_in_cart = true;
}
}
}
return $product_in_cart;
}
// Force Coupon codes for Woocommerce
add_action('woocommerce_check_cart_items', 'force_coupon_code');
function force_coupon_code($product_in_cart)
{
global $woocommerce;
if(is_cart() || is_checkout()){
$my_coupon = $woocommerce->cart->applied_coupons;
echo $woocommerce->cart->get_applied_coupons;
if(empty($my_coupon))
{
wc_add_notice('<strong>' . $btn['label'] . '</strong> ' . __('A coupon code is mandatory for this product.', 'woocommerce'), 'error');
}
}
}
第一部分應退回產品$ product_in_cart和第二部分迫使優惠券。這是我使用的代碼的來源。 Mandatory Coupon code和Checking products in cart based on category。我讀到將變量放在新函數args中可能會達到這個like so,但它絕不是工作。
美麗!發揮魅力。我還在學習,所以除了更好的代碼之外,'if(empty($ my_coupon)&& $ has_cat)'這一行就是將它們連接在一起。理論上,我可以在語句中添加更多的參數,並進一步縮小範圍,例如if(empty($ my_coupon)&& $ has_cat)&& $ color_blue && etc ...'? – jimmyjames