Offering free gifts for high-rated items will encourage customers to explore and purchase products with better ratings. This customization can be an effective marketing strategy to encourage sales and can be useful to highlight high-reviewed products in your store.
The purpose of this code is to add a free product to the cart if any of the products in the cart have an average rating equal to or greater than a specified minimum rating in the code($min_rating = 4).
function ts_add_free_product_for_high_rated( $cart ) { // Define the product ID of the free product to be added $free_product_id = 470; // Replace with the actual ID of your free product // Define the minimum rating for a product to be considered "high-rated" $min_rating = 4; // Change this to your desired minimum rating // Loop through cart items foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) { $product_id = $cart_item['product_id']; // Check if the product has a high rating $average_rating = get_post_meta( $product_id, '_wc_average_rating', true ); if ( $average_rating >= $min_rating ) { // Check if the free product is not already in the cart $free_product_in_cart = false; foreach ( $cart->get_cart() as $item ) { if ( $item['product_id'] === $free_product_id ) { $free_product_in_cart = true; break; } } // Add the free product to the cart if not already added if ( ! $free_product_in_cart ) { $cart->add_to_cart( $free_product_id ); } break; // Stop looping after adding the free product once } } } add_action( 'woocommerce_before_calculate_totals', 'ts_add_free_product_for_high_rated' );
Output
When the customer adds a high-rated item to the cart and if the rating matches the min_rating as set in the code, then the free product gets automatically added to the cart. Let’s have a look at the shop page and add a high-rated product to the cart as shown in the image.
Let’s look into another scenario where a customer adds an average-rated product to the cart and the free product doesn’t get added in such scenarios.
The below image shows that when an average/low rated products, i.e the rating of these products are less than 4 are added to the cart, the free product is not added.
Similarly, you can also apply bogo buy one get one offer based on product tags in WooCommerce cart.