Adding an ad product when reaching a certain basket amount

I'm looking for the right hook in WooCommerce because I need to add an ad product to the cart when a certain volume of the cart is reached, for example 100 conventional units.

I also used hook 'init' , but I do not think this is correct.

Here is my code:

 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 should be used for this purpose?

Or could you give me a link to some similar problem?

thanks

+5
source share
1 answer

When you aim a certain basket amount to add an advertising product to a basket, you can use woocommerce_before_calculate_totals to achieve this with a special function.

You should also remove this promo item if the client updates the cart (which is also built into this custom function).

Here is the code:

 add_action( 'woocommerce_before_calculate_totals', 'adding_promotional_product', 10, 1 ); function adding_promotional_product( $cart_object ) { if ( is_admin() && ! defined( 'DOING_AJAX' ) ) 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_object->is_empty() ){ // Iterating through each item in cart foreach ($cart_object->get_cart() as $item_key => $item_values ){ // If Promo product is in cart if( $item_values['data']->id == $promo_id ) { $has_promo = true; $promo_key= $item_key; } else { // Adding subtotal item to global subtotal $subtotal += $item_values['line_subtotal']; } } // If Promo product is NOT in cart and target subtotal reached, we add it. if( !$has_promo && $subtotal >= $targeted_cart_subtotal ) { $cart_object->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_object->remove_cart_item($promo_key); } } } 

This code continues the function.php file of your active child theme (or theme) or in any plugin file.

This code has been verified and works.

Related branch: WooCommerce - Automatically add or automatically remove product from cart

Code Updated (2017-04-19)

+8
source

Source: https://habr.com/ru/post/1257640/


All Articles