daily pastebin goal
68%
SHARE
TWEET

WooCommerce - Auto add item to cart if threshold reached

lorro Feb 9th, 2017 76 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <?php
  2.   // Auto add-to-cart when total reaches a given amount
  3.   // code goes in functions.php for your child theme
  4.   add_action( 'woocommerce_cart_loaded_from_session', 'auto_add_free_product_to_cart', 40 );
  5.   function auto_add_free_product_to_cart() {
  6.     // site owner's data
  7.     $min_cart_total = 100.00; // minimum cart value to qualify for the product
  8.     $free_product_id = 1801; // your free product ID here
  9.     if ( ! is_admin() ) { // do nothing if on dashboard
  10.       $woocommerce = WC(); // avoid globals
  11.       // find out if the product is already in the cart
  12.       $found = false;
  13.       foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $value ) {
  14.         $_product = $value['data'];
  15.         if ( $_product->id == $free_product_id ){
  16.           $found = true;
  17.         }
  18.       }
  19.       $cart_total = $woocommerce->cart->cart_contents_total;
  20.       if ($cart_total >= $min_cart_total) {
  21.         // cart total is enough
  22.         if ( !$found ) {
  23.           // free product not found, so add it
  24.           $woocommerce->cart->add_to_cart( $free_product_id );
  25.         }
  26.       } else {
  27.        // cart total is not enough, maybe an item was deleted      
  28.         if ( $found ) {
  29.           // user is not entitled to the free product
  30.           $woocommerce->cart->remove_cart_item( $cart_item_key );
  31.         }
  32.       }  
  33.     }
  34.   }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top