Create a lightweight commerce cart block
The .module file
We build a custom block and use hook_theme to render the cart data. Usually a view is made to create a custom shopping cart block. However, a custom block to render number of items and the total price of an order is more exciting to make and more performant than a view.
As page cache is disabled by commerce, which sets cookies, only block cache is activated. By setting cache to DRUPAL_NO_CACHE, cache is disabled for this particular block.
/**
* Implements hook_block_info().
*/
function commerce_general_block_info() {
$blocks['commerce_general_shopping_cart'] = array(
'info' => t('CG - Shopping cart'),
'title' => '',
'theme' => variable_get('theme_default', 'bartik'),
'region' => 'header',
'cache' => DRUPAL_NO_CACHE,
);
return $blocks;
}
/**
* Implements hook_block_view().
*/
function commerce_general_block_view($delta = '') {
switch ($delta) {
case 'commerce_general_shopping_cart':
return array(
'subject' => t('CG - Shopping cart'),
'content' => theme(
'commerce_general_shopping_cart',
array(
'cart' =>_commerce_general_get_shopping_cart_data()
)
),
);
break;
}
}
/**
* Implements hook_theme().
*/
function commerce_general_theme($existing, $type, $theme, $path) {
return array(
'commerce_general_shopping_cart' => array(
'template' => 'commerce_general_shopping_cart',
'arguments' => array('cart' => array())
)
);
}
/**
* Retrieve the current customers lightweight shopping cart data.
*/
function _commerce_general_get_shopping_cart_data() {
global $user;
$data = array();
$order = commerce_cart_order_load($user->uid);
if ($order) {
$quantity = 0;
$wrapper = entity_metadata_wrapper('commerce_order', $order);
$line_items = $wrapper->commerce_line_items;
$data['quantity'] = commerce_line_items_quantity($line_items, commerce_product_line_item_types());
$total = commerce_line_items_total($line_items);
$data['price'] = commerce_currency_format($total['amount'], $total['currency_code']);
}
return $data;
}
The template file
<div>
<?php if(!isset($cart['quantity'])): ?>
<?php print t('Your shopping cart is empty'); ?>
<?php else: ?>
<?php print format_plural($cart['quantity'], t('1 item'), t('@count items'));?>
<?php print t('Order total: ') ?><?php print $cart['price']; ?>
<?php endif; ?>
<a href="/cart"><?php print t('Cart'); ?></a>
</div>