0

I have set a threshold of 3 items for someone in the UK to get Free Shipping. Every time someone adds a product from a specific category, I automatically add a product to their cart which is a free gift.

My issue is that I am trying to exclude this free gift from the threshold count as currently this is being counted and people are getting free shipping without having 3 actual chargeable items in their cart.

I am unsure to how I can exclude product id 29 from counting, so any help would be greatly appreciated.

add_action( 'woocommerce_before_cart', 'ds_free_shipping_cart_notice' );
  
function ds_free_shipping_cart_notice() {
    $threshold = 3;
    $current = WC()->cart->get_cart_contents_count();
    $billing_country = WC()->customer->get_billing_country();
    if ( $current < $threshold && WC()->customer->get_billing_country() == 'GB' ) {
        wc_print_notice( 'Nearly there! Order ' . ( $threshold - $current ) . ' more and shipping is on us', 'notice' );
    }
    
}
kyarauk
  • 3
  • 4

1 Answers1

0

I don't have woocommerce set up to be able to test this, but this is the type of logic you need:

$cart_items = WC()->cart->get_cart();
$current = WC()->cart->get_cart_contents_count();
foreach($cart_items as $item => $values) { 
  if ($values['product_id'] == 29) {
   --$current;
  }
} 

This answer should help as well.

In general, though, this is a pretty fragile approach as you will need to change the hard-coded product ID every time you offer a new gift. It would be better to add a custom field to your products called "Free Gift" or something similar, set that value as needed for the items offered as free gifts, and then set up the code to exclude any of those items from the free shipping.

jdaz
  • 5,964
  • 2
  • 22
  • 34
  • Thank you, I added this and although product id 29 is not being counted, when I change the quantity of an item already in the cart, this isn't being counted which it does without your bit. Any idea? As for the free product, there will just be this one as it's for a particular category so that is okay. – kyarauk Jul 12 '20 at 18:20
  • Ok if that is happening maybe it is better to reverse the logic. Please take a look at my edited answer. – jdaz Jul 12 '20 at 18:50
  • 1
    You are an absolute star!! Thank you so much. It works as expected, I removed the $current in your answer as that was already part of the original code. Thank you again. – kyarauk Jul 12 '20 at 18:59
  • Please mark my answer as accepted if you wouldn’t mind, by clicking the big check mark next to it – jdaz Jul 13 '20 at 03:00
  • No problem, happy to help! – jdaz Jul 15 '20 at 04:13