Ubercart 3 - How to alter items in your cart

Profile picture for user Phil Frilling
By Phil Frilling, 3 February, 2012
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:

function MYMODULE_entity_load($entities, $type) {
  if ($type == 'uc_cart_item') {
    foreach ($entities as $item_id => $item) {
      if (sizeof($item->role_prices)) {
        // Make your modifications here.
        $item->price = $item->sell_price;
      }
    }
  }
}