Advertisement
majeedraza

WooCommerce - Auto add item to cart if threshold reached

Feb 9th, 2017
272
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.34 KB | None | 0 0
  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.   }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement