Skip to content

Instantly share code, notes, and snippets.

@eighty20results
Last active November 21, 2017 07:26
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 eighty20results/0495a4b150feb019f70325760788b919 to your computer and use it in GitHub Desktop.
Save eighty20results/0495a4b150feb019f70325760788b919 to your computer and use it in GitHub Desktop.
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