The code below auto add a product to cart in WooCommerce:
add_action( 'template_redirect', 'add_product_to_cart' ); function add_product_to_cart() { if ( ! is_admin() ) { $product_id = 64; $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 ); } } }
The answer Checking if customer has already bought something in WooCommerce allows to check if user has already make a purchase or not with a custom conditional function has_bought()
.
So what I would like is to check if the customer has ordered before and:
- If it’s their first order, force product A into the cart OR
- If they’ve already made one or more purchases, force product B into the cart
But I didn’t find the way to use it in my code.
Any help will be appreciated.
Advertisement
Answer
The code below uses the custom function has_bought()
. It auto add to cart a different product for new customers and confirmed customers:
add_action( 'template_redirect', 'add_product_to_cart_conditionally' ); function add_product_to_cart_conditionally() { if ( is_admin() ) return; // Exit // Below define the product Id to be added: $product_A = 37; // <== For new customers that have not purchased a product before (and guests) $product_B = 53; // <== For confirmed customers that have purchased a product before $product_id = has_bought() ? $product_B : $product_A; // If cart is empty if( WC()->cart->is_empty() ) { WC()->cart->add_to_cart( $product_id ); // Add the product } // If cart is not empty else { // Loop through cart items (check cart items) foreach ( WC()->cart->get_cart() as $item ) { // Check if the product is already in cart if ( $item['product_id'] == $product_id ) { return; // Exit if the product is in cart } } // The product is not in cart: We add it WC()->cart->add_to_cart( $product_id ); } }
Code goes in functions.php file of the active child theme (or active theme). Tested and works.
Related: Checking if customer has already bought something in WooCommerce