This customization is extremely useful in clearing out products that have very low sales count. When such products are tied to Buy One Get One offers, it helps to make room for seasonal or new arrivals, avoiding the risk of selling outdated or out-of-season items. This code will offer a free product when a product with a low sales count is added to the cart.
function ts_offer_free_product_based_on_sales_count( $item_key, $product_id ) { // Define the threshold for low sales count $low_sales_threshold = 5; // Get the sales count for the product $sales_count = get_post_meta( $product_id, 'total_sales', true ); // Check if the product has a low sales count if ( $sales_count && $sales_count <= $low_sales_threshold ) { $free_product_id = 470; // Product Id of the free product which will get added to cart // Check if the free product is not already in the cart $found = false; foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) { $_product = $values['data']; if ( $_product->get_id() == $free_product_id ) { $found = true; break; } } // If the free product is not found, add it to the cart if ( ! $found ) { WC()->cart->add_to_cart( $free_product_id ); } } } // Hook to add free product based on sales count add_action( 'woocommerce_add_to_cart', 'ts_offer_free_product_based_on_sales_count', 10, 2 );
Output
Let’s find out how the total sales of a product is determined for a product from the backend.
As the total sales count of the above product is less than the threshold set in the code ($low_sales_threshold = 5), the free product is added automatically whenever this product is added to the cart.
Alternatively, you can also add bogo buy one get one for high-rated products in WooCommerce.