Search code examples
phpwordpresswoocommercecartproduct

Auto add a Product to Cart in Woocommerce 3


I would like that anybody who visits my Woocommerce shop finds a free product in his cart. I found this code and it works but it shows many php errors in logs.

Do you have an idea why is not "clean"?

Any help on this please.

/*
 * AUTOMATICALLY ADD A PRODUCT TO CART ON VISIT
 */
function aaptc_add_product_to_cart() {
    if ( ! is_admin() ) {
        $product_id = 99999;  // Product Id of the free product which will get added to cart
        $found  = false;
        //check if product already in cart
        if ( sizeof( WC()->cart->get_cart() ) > 0 ) {
            foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
                $_product = $values['data'];
                if ( $_product->get_id() == $product_id )
                    $found = true;
            }
            // if product not found, add it
            if ( ! $found )
                WC()->cart->add_to_cart( $product_id );
        } else {
            // if no products in cart, add it
            WC()->cart->add_to_cart( $product_id );
        }
    }
}
add_action( 'init', 'aaptc_add_product_to_cart' );

Solution

  • Try instead this revisited similar code using template_redirect action hook:

    add_action( 'template_redirect', 'auto_add_product_to_cart' );
    function auto_add_product_to_cart() {
        if ( is_admin() ) return;
    
        // Product Id of the free product which will get added to cart;
        $product_id = 99999;
    
        if ( WC()->cart->is_empty() ) 
        {
            // No products in cart, we add it
            WC()->cart->add_to_cart( $product_id ); 
        } 
        else
        {
            $found  = false;
    
            //check if product already in cart
            foreach ( WC()->cart->get_cart() as $cart_item ) {
                if ( $cart_item['data']->get_id() == $product_id )
                    $found = true;
            }
    
            // if the product is not in cart, we add it
            if ( ! $found )
                WC()->cart->add_to_cart( $product_id ); 
        }
    }
    

    Code goes in function.php file of your active child theme (or active theme). Tested and works.

    Note: The init hook is not correct here and not to be used for this…