Skip to main content

Ubercart 3 - How to alter items in your cart

I'm building an e-commerce website and I decided to use Drupal 7 and Ubercart. During development I discovered that Ubercart 2's function, hook_cart_item, was no longer available to Drupal 7. This led me to the question:

How do I alter an Ubercart cart item with Drupal 7?

A quick glance through the issue queue led me to this article, http://drupal.org/node/1424852, which, in a nutshell, states that we can accomplish this by using Drupal 7's Entity API (http://api.drupal.org/api/drupal/modules--system--system.api.php/7).

A quick glance through the system.api.php documentation led me to hook_entity_api, and the solution to my problem. To alter cart items use the function below:

  1. function MYMODULE_entity_load($entities, $type) {
  2.   if ($type == 'uc_cart_item') {
  3.     foreach ($entities as $item_id => $item) {
  4.       if (sizeof($item->role_prices)) {
  5.         // Make your modifications here.
  6.         $item->price = $item->sell_price;
  7.       }
  8.     }
  9.   }
  10. }


Comments