Skip to content

Instantly share code, notes, and snippets.

@braddalton
Created June 10, 2024 04:55
Show Gist options
  • Save braddalton/d306bd3e8702fe403be0de6c80519fdf to your computer and use it in GitHub Desktop.
Save braddalton/d306bd3e8702fe403be0de6c80519fdf to your computer and use it in GitHub Desktop.
Automatically add an extra product to the cart when a specific product is added in WooCommmerce
add_action('woocommerce_before_calculate_totals', 'ensure_two_products_in_cart');
function ensure_two_products_in_cart($cart) {
if (is_admin() && !defined('DOING_AJAX')) return;
// Replace '123' with the ID of the product you want to ensure is sold in twos
$product_id = 123;
$quantity_to_add = 2;
foreach ($cart->get_cart() as $cart_item_key => $cart_item) {
if ($cart_item['product_id'] == $product_id) {
if ($cart_item['quantity'] < $quantity_to_add) {
$cart_item['quantity'] = $quantity_to_add;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment