Programmatically add product in cart - empty cart

Camital picture Camital · Dec 12, 2013 · Viewed 9.9k times · Source

I'm trying to add a product in cart but the cart stay empty. Here's my code

try{
    $product_model = Mage::getSingleton('catalog/product');

    // Load product
    $_sku = "1-574#AD-B00731";
    $my_product_id  = $product_model->getIdBySku($_sku);
    $my_product     = $product_model->load($my_product_id);
    $qty_value = 1;

    // Add to cart 
    $cart = Mage::getModel('checkout/cart');
    $cart->init();
    $cart->addProduct($my_product, array('qty' => $qty_value));
    $cart->save();
    print_r($cart->getItemsQty().PHP_EOL);
    Mage::getSingleton('checkout/session')->setCartWasUpdated(true);
    var_dump("working");
 }
catch(Exception $e){
    return $e->getMessage();
}

When I print $cart->getItemsQty() my item quantity are incremanting but my cart is still empty. I think it's Mage::getSingleton('checkout/session')->setCartWasUpdated(true); that is not working properly.

Anybody have an idea of what is not working?

Edit 1: I use Magento 1.8.0, so via an url query is not working because of the form_key

Answer

freento picture freento · Dec 12, 2013

Try to change

$cart = Mage::getModel('checkout/cart');

to

$cart = Mage::getSingleton('checkout/cart');

Cart is a singleton, because you have only 1 cart on your store for 1 user and all who want to use it can call it as getSingleton, without creating new object. If you use Mage::getModel('checkout/cart') it will create a new object. Ye, it will allow you to save quote to DB, but this will not be current active customer cart.