Taras  Bezdushnuy Taras Bezdushnuy - 1 year ago 66
PHP Question

Adding a promotional product when a certain cart amount is reached

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.

I have also used the hook

but I do not think it's right.

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;
$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?


Answer Source

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.

You have also to remove that promo item if customer update the cart (which is embed in that custom function too).

Here is the code:

add_action( 'woocommerce_before_calculate_totals', 'adding_promotional_product', 10, 1 );
function adding_promotional_product( $cart_object ) {

    $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->cart_contents as $key => $cart_item ){

            // If Promo product is in cart
            if( $cart_item['data']->id == $promo_id ) {
                $has_promo = true;
                $promo_key= $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 ) {
            echo 'add';
        // If Promo product is in cart and target subtotal is not reached, we remove it.
        } elseif( $has_promo && $subtotal < $targeted_cart_subtotal ) {

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.

Related thread: WooCommerce - Auto add or auto remove a freebie product from cart

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download