【发布时间】:2017-01-07 03:31:34
【问题描述】:
我正在经营一家 WooCommerce 商店,我们希望在您将产品明显添加到购物篮后,为每位客户提供一份免费赠品(电子书),该赠品将显示在购物篮中。
示例:
您将“product1”添加到购物篮,现在购物篮将显示 2 个产品。 “product1”和“freebie”。
当您从购物篮中取出产品时,赠品将再次被取出。
我现在得到了这个代码:
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);
}
}
但它似乎还没有完全起作用。
我做错了什么?
任何帮助将不胜感激。
【问题讨论】:
-
谢谢,我会尽快处理的。
标签: php wordpress woocommerce cart product