Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- // Auto add-to-cart when total reaches a given amount
- // code goes in functions.php for your child theme
- add_action( 'woocommerce_cart_loaded_from_session', 'auto_add_free_product_to_cart', 40 );
- function auto_add_free_product_to_cart() {
- // site owner's data
- $min_cart_total = 100.00; // minimum cart value to qualify for the product
- $free_product_id = 1801; // your free product ID here
- if ( ! is_admin() ) { // do nothing if on dashboard
- $woocommerce = WC(); // avoid globals
- // find out if the product is already in the cart
- $found = false;
- foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $value ) {
- $_product = $value['data'];
- if ( $_product->id == $free_product_id ){
- $found = true;
- }
- }
- $cart_total = $woocommerce->cart->cart_contents_total;
- if ($cart_total >= $min_cart_total) {
- // cart total is enough
- if ( !$found ) {
- // free product not found, so add it
- $woocommerce->cart->add_to_cart( $free_product_id );
- }
- } else {
- // cart total is not enough, maybe an item was deleted
- if ( $found ) {
- // user is not entitled to the free product
- $woocommerce->cart->remove_cart_item( $cart_item_key );
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement