Last active
October 30, 2017 11:55
-
-
Save vanbo/f42cfa8bdf593013f77dda605a9876bb to your computer and use it in GitHub Desktop.
Add a product and quantity to cart, based on another product and quantity.
This file contains 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
add_action( 'woocommerce_add_to_cart', 'prefix_add_additional_product', 10, 6 ); | |
/** | |
* Adds additional product to cart based on the quantity of an added product | |
*/ | |
function prefix_add_additional_product( $cart_item_key, $product_id, $quantity, $variation_id, $variation, $cart_item_data ) { | |
// Get the cart | |
$cart = WC()->cart->get_cart(); | |
// Nothing, if the cart is empty | |
if ( 0 == count( $cart ) ) { | |
return; | |
} | |
// Enter the free product ID | |
$additional_product_id = 96; | |
// Don't add accessory when adding the same accessory | |
$added_product_id = 0 < $variation_id ? $variation_id : $product_id; | |
if ( $added_product_id == $additional_product_id ) { | |
return; | |
} | |
// You can add checks for specific product ID or some other requirements here | |
$additional_product_quantity = (int) ( $quantity / 5 ); | |
WC()->cart->add_to_cart( $additional_product_id, $additional_product_quantity ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment