本文介绍了woocommerce 买一送一,无需优惠码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望在用户购买 x 产品时在我的网站上实现功能,然后用户将免费获得 y 产品.

I want implement functionality on my site when user buy a x product then user will get a y product as free.

在我的网站中,我有多种产品.如果客户购买 1 公斤包装的 X 产品,那么客户想要免费获得 30 毫升的 Y 产品.

In my site i have variable products.If customer buy 1kg pack of X product then customer want to get Free 30ml of Y product.

我在我的 function.php 中添加了以下代码,但它的工作问题是刷新页面礼品产品数量增加时.我更新的代码.

I added below code in my function.php but its working the problem is when refreshing the page gift product count is increasing.my updated code.

    add_action( 'woocommerce_before_cart', 'bbloomer_apply_matched_coupons' );

function bbloomer_apply_matched_coupons() {

    global $woocommerce;
 $cat_in_cart = false;
    foreach ( $woocommerce->cart->cart_contents as $key => $values ) {

    // this is your product ID
    $autocoupon = array( 123411 );

    if( in_array( $values['variation_id'], $autocoupon ) ) {  
       $cat_in_cart = true;
        break;

    }


    }
 if ( $cat_in_cart ) {   
$product_id   = 2044;
$quantity     = 1;
$variation_id = 2046;
$variation    = array(
    'pa_size'  => '30ml'
);

$woocommerce->cart->add_to_cart( $product_id, $quantity, $variation_id, $variation );
 }

}

推荐答案

将此添加到 'functions.php' 的开头.

Add this to start of 'functions.php'.

ob_start();
session_start();

然后添加此代码.

add_action( 'woocommerce_before_cart', 'bbloomer_apply_matched_coupons' );

function bbloomer_apply_matched_coupons() {

    if(!$_SESSION['GiftAdded']) {
        global $woocommerce;
        $cat_in_cart = false;
        $coupon_in_cart = false;

        $autocoupon = array( 123411 ); // variation ids of products that offers gifts
        $freecoupon = array( 2046 ); // variation ids of products that are gift coupons

        foreach ( $woocommerce->cart->cart_contents as $key => $values ) {      
            if( in_array( $values['variation_id'], $autocoupon ) ) {  
                $cat_in_cart = true;                
            }
            if( in_array( $values['variation_id'], $freecoupon) ) {  
                $coupon_in_cart = true;             
            }
        }

         if ( $cat_in_cart && !$coupon_in_cart ) {   
            $product_id   = 2044;
            $quantity     = 1;
            $variation_id = 2046;
            $variation    = array( 'pa_size'  => '30ml' );

            $woocommerce->cart->add_to_cart( $product_id, $quantity, $variation_id, $variation );
            $_SESSION['GiftAdded']=true;
        }
    }
}

$_SESSION['GiftAdded'] 将阻止手动删除的礼品产品再次添加.

The $_SESSION['GiftAdded'] will prevent the gift product added again when its deleted manually.

这篇关于woocommerce 买一送一,无需优惠码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 00:30