Skip to content

Instantly share code, notes, and snippets.

@MaffooBristol
Last active December 15, 2015 16:58
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 MaffooBristol/65f8057f8ff44c28c768 to your computer and use it in GitHub Desktop.
Save MaffooBristol/65f8057f8ff44c28c768 to your computer and use it in GitHub Desktop.
Example of merging commerce orders/carts with hook_commerce_cart_order_convert()
<?php
// Thanks to http://jasonrichardsmith.org/blog/drupal-commerce-merge-anonymous-carts-when-logging
// for the code on which this is based!
function yourmodule_commerce_cart_order_convert($anon_cart, $account) {
$user_cart = commerce_cart_order_load($account->uid);
if (!$user_cart) {
return;
}
$user_cart = entity_metadata_wrapper('commerce_order', $user_cart);
// Loop through anonymous cart line items.
foreach ($anon_cart->commerce_line_items as $line_item) {
// Create an exists flag, which will prevent the whole line item
// being copied across if it can merge the quantity fields instead.
$exists = FALSE;
// Loop through our old, logged-in cart line items.
foreach ($user_cart->commerce_line_items as $user_line_item) {
// If the a product in our old cart also exists in the new one,
// add their quantities together on the user cart and save the line item.
if ($line_item->commerce_product->product_id->value() === $user_line_item->commerce_product->product_id->value()) {
$user_line_item->quantity->set((float) $user_line_item->quantity->value() + (float) $line_item->quantity->value());
$user_line_item->save();
$exists = TRUE;
}
}
// Assuming that the product hasn't already been added, copy
// the entire line item over as it is. This is done by setting
// the line item's order_id to the user cart's id first, then adding
// it explicitly to the cart, and saving both line item and cart.
if (!$exists) {
$line_item->order_id = $user_cart->order_id->value();
$line_item->save();
$user_cart->commerce_line_items[] = $line_item;
}
}
// Save our old user cart with new/improved line items/products.
$user_cart->save();
// Can't delete the anon cart, because it's required for the
// next part of the conversion process, and if it doesn't exist
// then entity.inc will scream at you. Best to cancel and then
// remove with cron if desired.
$anon_cart->status->set('canceled');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment