Black Friday & Cyber Monday SUPER SALE ALL WEEK:
Grab 40% OFF on plugins
Days
Hours
Minutes
Seconds

How to Add BOGO (Buy One Get One) Offers for Products Purchased in the Last X Days in WooCommerce?

Offering complementary BOGO (Buy One Get One) offers to customers who have made previous purchases in the last ‘X’ days will lead to customer satisfaction and retention. This code helps you to automatically add a free product to a user’s cart if they have made a purchase in the last 30 days.

function ts_add_product_to_cart() {
    if (!is_admin() && is_user_logged_in()) {
        $free_product_id = 470; // Product ID of the free product to be added to cart
        $user_id = get_current_user_id();
        $found = false;

        // Check if the user has made a purchase in the last 30 days
        $last_30_days_orders = wc_get_orders(array(
            'customer' => $user_id,
            'date_query' => array(
                array(
                    'after' => date('Y-m-d', strtotime('-30 days')),
                ),
            ),
            'status' => 'completed', // Consider only completed orders
            'limit' => -1,
        ));

        if (count($last_30_days_orders) > 0) {
            // Check if there are any products in the cart
            if (sizeof(WC()->cart->get_cart()) > 0) {
                foreach (WC()->cart->get_cart() as $cart_item_key => $values) {
                    // Check if the cart item is not the free product
                    if ($values['data']->get_id() != $free_product_id) {
                        $found = true;
                        break;
                    }
                }
                // If a non-free product is found, add the free product to the cart
                if ($found) {
                    WC()->cart->add_to_cart($free_product_id);
                }
            }
        }
    }
}

add_action('template_redirect', 'ts_add_product_to_cart');

Output

When a custome is logged in , the code checks whether the current logged in user has completed orders in the last 30 days. and if such orders exist, the code proceeds to add the free product once the user adds any product to the cart.


How to Add BOGO (Buy One Get One) Offers for Products Purchased in the Last X Days in WooCommerce? - Tyche Softwares

Additionally, you can also offer such complementary gifts based on their total amount spent in their previous purchases. Check out this guide on how to add bogo buy one get one gifts to high value customers in WooCommerce.

Browse more in: Code Snippets, WooCommerce How Tos, WooCommerce Tutorials

Share It:

Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x