Add product to cart programmatically I want to add a product to the cart programmatically on form submit

My code below works only for root, but in my site an anonymous user can access the cart and checkout, but when submitting form with non user=1 it returns Your shopping cart is empty.

In my submit function: 

$uid = ($user-&gt;uid) ? $user-&gt;uid : 0;
    $order = commerce_order_new($uid, 'checkout_checkout');

// Save the order to get its ID.
    commerce_order_save($order);

// Load whatever product represents the item the customer will be
// paying for and create a line item for it.
    $product = commerce_product_load($product_id);

    $line_item = commerce_product_line_item_new($product, 1, $order-&gt;order_id);
// Save the line item to get its ID.
    commerce_line_item_save($line_item);
// Add the line item to the order using fago's rockin' wrapper.
    $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
    $order_wrapper-&gt;commerce_line_items[] = $line_item;

// Save the order again to update its line item reference field.
    commerce_order_save($order);
    //commerce_cart_order_refresh($order);
//    ym(commerce_cart_order_id($uid));
    //commerce_cart_commerce_order_load($order);
    //ym(commerce_cart_order_is_cart($order));
    //commerce_cart_product_add($uid, $line_item);
    //commerce_cart_product_add_by_id($product_id);
    //$form_state['redirect'] = 'cart';
    drupal_goto('cart');


Why does it not work correctly with non root (uid=1)?
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-&gt;uid: 0) Drupal Commerce manages the $_SESSION
 $line_item_added = commerce_cart_product_add($user-&gt;uid, $line_item);

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