Drupal - Add product to cart programmatically

You don't need to change the order directly, commerce_cart_product_add do it for you.

Try this code:

Variables:

 $product : commerce product
 $quantity: number of elements

Code

 global $user;
 // Create new line item:
 $line_item = commerce_product_line_item_new($product, $quantity);

 // Add to current user's cart: if the user is not logged in ($user->uid: 0) Drupal Commerce manages the $_SESSION
 $line_item_added = commerce_cart_product_add($user->uid, $line_item);

 // If $line_item_added !== FALSE the line_item has been added OK!

You need to add commerce_cart_order_session_save() so anonymous user have their session to link the browser with cart content.

Tags:

Commerce