Last active
August 2, 2021 10:47
-
-
Save fida02/99dcc772ac000cebf2f732b719b70674 to your computer and use it in GitHub Desktop.
WooCommerce Automatically add a gift product when customer purchase anything
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| /* | |
| * Automatically add a gift product when customer purchase anything. | |
| * Use: Add this code in your theme's function.php file | |
| */ | |
| function fida_add_gift_product_to_cart() { | |
| global $woocommerce; | |
| $cart_total = 1; | |
| if ( $woocommerce->cart->total >= $cart_total ) { | |
| if ( ! is_admin() ) { | |
| $gift_product_id = 40; // Gift product ID | |
| $found = false; | |
| //check if product already in cart | |
| if ( sizeof( WC()->cart->get_cart() ) > 0 ) { | |
| foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) { | |
| $_product = $values['data']; | |
| if ( $_product->get_id() == $gift_product_id ) | |
| $found = true; | |
| } | |
| // if product not found, add it | |
| if ( ! $found ) | |
| WC()->cart->add_to_cart( $gift_product_id ); | |
| } else { | |
| // if no products in cart, add it | |
| WC()->cart->add_to_cart( $gift_product_id ); | |
| } | |
| } | |
| } | |
| } | |
| add_action( 'template_redirect', 'fida_add_gift_product_to_cart' ); | |
| ?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment