back to blog

Add a Product to Cart Using a Custom Menu Callback

September 26th, 2014 by Daniel Pepin

Having a custom callback to add products to the user's cart can be very valuable.

You are able to create dynamic links that act as the built-in "Add to Cart" form.

We are going to create a callback such that add-to-cart/product/93/1 will add 1 item of product 93 to the user's cart. The callback will be setup so that the URL arguments will be:
1. add-to-cart (callback path).
2. Line item type (product is the standard line item type for commerce products).
3. Product ID
4. Quantity

In your custom module, create a hook_menu like so:

 * Implements hook_menu().
function custom_menu(){
  return array(
    'add-to-cart/%/%commerce_product/%' => array(
      'type' => MENU_CALLBACK,
      'page callback' => 'custom_add_to_cart',
      'page arguments' => array(1, 2, 3),
      'access callback' => TRUE, // Warning: Anyone can use this callback.

Next, we need to create our custom callback function:

 * Custom callback to add a product to the user's cart.
function custom_add_to_cart($line_item_type, $product, $quantity = 1) {
  global $user;
  $uid = $user->uid;
  // Get the order to add line items to.
  $order = commerce_cart_order_load($uid);
  if (!$order) {
    $order = commerce_cart_order_new($uid);
  // Add the product to the line item and create it.
  $line_item = commerce_product_line_item_new($product, $quantity, $order->order_id, array(), $line_item_type);
  // Add the line item to the cart.
  if(commerce_cart_product_add($uid, $line_item)) {

And that's basically it. Flush your menu cache, and the callback should add the product to the user's cart and then send the user to their cart.