Skip to content

Instantly share code, notes, and snippets.

@vanbo
Last active October 30, 2017 11:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vanbo/f42cfa8bdf593013f77dda605a9876bb to your computer and use it in GitHub Desktop.
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.
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