Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Add a new line item if the quantity of a product increases
function createUniqueLineItems( $cart_item_key, $product_id, $quantity, $variation_id, $variation, $cart_item_data ) {
// Only do this for quantities > 1
if ( $quantity > 1 ) {
// Reset the quantity for the current product entry
WC()->cart->set_quantity( $cart_item_key, 1 );
// Add a line-item for all quantities > 1. Already have one entry in the cart, so do it for $quantity - 1
for ( $i = 1; $i <= $quantity - 1; $i ++ ) {
//Probably doesn't work!
$new_cart_item_data = $cart_item_data;
$new_cart_item_data['_e20r_item_owner'] = $_SESSION['_e20r_item_owner'][$user_key];
// Generate a unique key for products w/quantity > 1 (separate line items)
$new_cart_item_data['unique_key'] = md5( microtime() . rand() . 'e20r-cart' );
// Add the 'extra' product line item
$new_cart_item_key = WC()->cart->add_to_cart( $product_id, 1, $variation_id, $variation, $new_cart_item_data );
}
}
}
add_action( 'woocommerce_add_to_cart', 'createUniqueLineItems', 10, 6 )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.