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

How to Add the Cheapest Products in WooCommerce Store as a BOGO(Buy One Get One)Offer?

This code snippet is useful in implementing a BOGO “Buy one Get One” offer based on the least expensive products available in the store.

// Hook to add action on template redirect
add_action('template_redirect', 'ts_add_cheapest_product_as_gift');

// Function to add cheapest product as a gift to the cart
function ts_add_cheapest_product_as_gift() {
    // Check if in admin or cart is empty
    if (is_admin()) return;
    if (WC()->cart->is_empty()) return;

    // Get the cart items
    $cart_items = WC()->cart->get_cart();

    // Initialize an array to store product IDs in the cart
    $product_ids_in_cart = array();

    // Get all product IDs in the cart
    foreach ($cart_items as $cart_item) {
        $product_ids_in_cart[] = $cart_item['product_id'];

    // If there are products in the cart, set $product_bought_id as the first product in the cart
    $product_bought_id = !empty($product_ids_in_cart) ? $product_ids_in_cart[0] : null;

    // Get the cheapest product from the entire catalog
    $cheapest_product = ts_get_cheapest_product();

    if ($cheapest_product) {
        $product_gifted_id = $cheapest_product->get_id();

        // See if product id is in cart
        $product_bought_cart_id = WC()->cart->generate_cart_id($product_bought_id);
        $product_bought_in_cart = WC()->cart->find_product_in_cart($product_bought_cart_id);

        // See if gift id is in cart
        $product_gifted_cart_id = WC()->cart->generate_cart_id($product_gifted_id);
        $product_gifted_in_cart = WC()->cart->find_product_in_cart($product_gifted_cart_id);

        // If not in cart, remove gift; else, add gift
        if (!$product_bought_in_cart) {
            if ($product_gifted_in_cart) WC()->cart->remove_cart_item($product_gifted_in_cart);
        } else {
            if (!$product_gifted_in_cart) WC()->cart->add_to_cart($product_gifted_id);

// Function to get the cheapest product from the entire catalog
function ts_get_cheapest_product() {
    global $wpdb;

    $query = "SELECT post_id FROM {$wpdb->postmeta} WHERE meta_key = '_price' AND meta_value > 0 ORDER BY CAST(meta_value AS SIGNED) ASC LIMIT 1";

    $product_id = $wpdb->get_var($query);

    if ($product_id) {
        return wc_get_product($product_id);

    return null;


When customers adds any products to the cart, the cheapest product available in the store gets added as the free product.

How to Add the Cheapest Products in WooCommerce Store as BOGO Offer

Similarly, you can also automatically add a free product to your WooCommerce cart based on 6 different conditions such as cart total, categories, on website visit, etc

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

Share It:

Notify of
Inline Feedbacks
View all comments
Would love your thoughts, please comment.x