Magento Add to Cart – Fix Adding to Wrong Store in Magento 1.9

addtocartmagento-1.9multistore

I'm trying to add to cart programmatically from store 2, but it's adding products to store 1. How can I force it to add to the correct store?

This is the code I've got in my CMS page.

include_once "app/Mage.php";
umask(0);
Mage::app();
Mage::getSingleton('core/session');

$product_id = '1658';
$qty = '1';
$product = Mage::getModel('catalog/product')->load($product_id);
$cart = Mage::getSingleton('checkout/session')->getQuote();
$cart->addProduct($product, $qty);
$cart->save();
Mage::getSingleton('core/session')->addSuccess('Art Hanging System added to cart successfully. Enjoy!');

I've tried using Mage::app()->setCurrentStore(2), but this ends up adding the success message to the 1st store still and not adding the product to either site's cart.

I've tried every way I can find or think of, but as soon as I try to specify the 2nd store, then nothing happens.

How can I specify which site's cart I'm trying to work with?

Best Answer

Try setting the store scope when declaring your $cart variable, as below:

$cart = Mage::getSingleton('checkout/session')->setStoreId(2)->getQuote();

This forces Magento to load the quote object from store with ID 2 (or whatever you put between the brackets).