我經營的是一家WooCommerce商店,我們希望爲每位顧客提供一個免費贈品(電子書)一個產品到籃子明顯。WooCommerce - 自動添加或自動刪除購物車中的免費贈品產品
示例:
您將「product1」添加到購物籃中,購物籃現在顯示2件商品。 「產品1」和「免費贈品」。 當您從籃子中取出產品時,免費贈品將再次被移除。
我得到這個代碼現在:
add_action('woocommerce_add_to_cart', 'check_freebie_exists', 10, 6);
function check_freebie_exists($cart_item_key, $product_id, $quantity, $variation_id, $variation, $cart_item_data) {
if($product_id == 1234) { // obviously replace this with the product that triggers the freebie
/* or you could use
if(has_term($cat_id, 'product_cat', $product_id)) { to check if a product is in a particular product_cat
or you could check anything else related to the product
*/
$hasfreebie = false;
// loop through the cart to check the freebie is not already there
global $woocommerce;
$cart = $woocommerce->cart->get_cart();
foreach($cart as $key => $values) {
if($values['data']->id == $your_freebie_product_id) {
$hasfreebie = true;
break;
}
}
if(!$hasfreebie) {
$woocommerce->cart->add_to_cart($your_freebie_product_id);
}
}
}
add_action('woocommerce_cart_item_removed', 'remove_freebie', 10, 2);
function remove_freebie($cart_item_key, $cart) {
$hasmaster = false;
$freebiekey = NULL;
foreach($cart as $key => $values) {
if($values['data']->id == 1234) { // check that we have the product that should trigger the freebie
$hasmaster = true;
} elseif($values['data']->id == $your_freebie_product_id) {
$freebiekey = $key;
}
}
if(!$hasmaster && $freebiekey) {
$cart->remove_cart_item($freebiekey);
}
}
但它似乎並沒有被工作相當尚未。
我做錯了什麼?
任何幫助將非常感激。
謝謝。
謝謝,我會盡快做到。 –