当达到一定数量的购物车时添加促销产品 [英] Adding a promotional product when a certain cart amount is reached
问题描述
我正在WooCommerce中寻找合适的选择,因为当达到一定数量的购物车(例如100个常规单位)时,我需要在购物车中添加促销产品。
I am looking for the right hook in WooCommerce because I need to add a promotional product to the cart when a certain cart amount of is reached, such as 100 conventional units.
我也使用了钩子 'init'
,但我认为这是不对的。
I have also used the hook 'init'
but I do not think it's right.
这是我的代码:
function add_free_product_to_cart(){
global $woocommerce;
$product_id = 2006;
$found = false;
if ( sizeof( $woocommerce->cart->get_cart() ) > 0 )
{
foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values )
{
$_product = $values['data'];
if ( $_product->id == $product_id )
$found = true;
}
if(!$found)
{
$maximum = 100;
$current = WC()->cart->subtotal;
if($current > $maximum){
$woocommerce->cart->add_to_cart( $product_id );
}
}
}
}
add_action( 'woocommerce_add_to_cart', 'add_free_product_to_cart' );
我应该为此使用哪个钩子?
which hook I should use for that purpose?
或者您能给我一个指向类似问题的链接吗?
Or could you give me a related link to to some similar problem?
谢谢
推荐答案
由于您要确定一定数量的购物车以在购物车中添加促销产品,因此可以使用
woocommerce_before_calculate_totals
挂钩可通过自定义的内置功能来实现此目的。
As you are targeting a certain cart amount to add a promotional product in the cart, you could use
woocommerce_before_calculate_totals
hook to achieve this with a custom built function.
如果客户更新购物车(也嵌入在该自定义功能中),您还必须删除该促销商品。。
以下是代码:
add_action( 'woocommerce_before_calculate_totals', 'adding_promotional_product', 10, 1 );
function adding_promotional_product( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
$promo_id = 99; // <=== <=== <=== Set HERE the ID of your promotional product
$targeted_cart_subtotal = 100; // <=== Set HERE the target cart subtotal
$has_promo = false;
$subtotal = 0;
if ( ! $cart->is_empty() ){
// Iterating through each item in cart
foreach ($cart->get_cart() as $item_key => $cart_item ){
$product_id = version_compare( WC_VERSION, '3.0', '<' ) ? $cart_item['data']->id : $cart_item['data']->get_id();
// If Promo product is in cart
if( $product_id == $promo_id ) {
$has_promo = true;
$promo_key= $item_key;
} else {
// Adding subtotal item to global subtotal
$subtotal += $cart_item['line_subtotal'];
}
}
// If Promo product is NOT in cart and target subtotal reached, we add it.
if( ! $has_promo && $subtotal >= $targeted_cart_subtotal ) {
$cart->add_to_cart( $promo_id );
// echo 'add';
// If Promo product is in cart and target subtotal is not reached, we remove it.
} elseif( $has_promo && $subtotal < $targeted_cart_subtotal ) {
$cart->remove_cart_item( $promo_key );
}
}
}
此代码可以继续运行。您的活动子主题(或主题)或任何插件文件中的php文件。
This code goes on function.php file of your active child theme (or theme) or in any plugin file.
此代码经过测试并可以正常工作。
This code its tested and works.
相关线程: WooCommerce-自动添加或从购物车中删除免费赠品产品
上的代码已更新(2018-10- 01)
这篇关于当达到一定数量的购物车时添加促销产品的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!