Magento CE 18.104.22.168
I've cobbled together a very simple up-sell function using PHP and I'm trying to determine how to proceed with implementing it.
The details of the function: User adds a simple product (no options) to cart then clicks "Proceed to Checkout" during which time a modal window pops up showing an image and details of the up-sell option. They can click "No Thanks" and proceed to normal checkout URL or they can click "Add to Cart" which will replace the product in there cart with the better/upsell version and automatically go to checkout.
The latter part - Add to Cart - requires PHP and at this point a page refresh in order for it to work. This code modifies the cart contents. In my crude attempt to resolve the issue, I've made it so that when the user Clicks "Add to Cart" it will send them to an empty CMS page where it processes the PHP and then sends them to the checkout. Almost imperceptible in production but I'm assuming there is a better way to trigger a function or event containing PHP. Here is my code:
<?php // Delete base product $id = '123'; // this is the product I am removing $cartHelper = Mage::helper('checkout/cart'); $items = $cartHelper->getCart()->getItems(); foreach($items as $item): if($item->getProduct()->getId() == $id): $itemId = $item->getItemId(); $cartHelper->getCart()->removeItem($itemId)->save(); break; endif; endforeach; ?> <?php // Add upsold product and qty $id = '321'; // Adds upsold product to cart $qty = '1'; // Choose how many products to add $_product = Mage::getModel('catalog/product')->load($id); $cart = Mage::getModel('checkout/cart'); $cart->init(); $cart->addProduct($_product, array('qty' => $qty)); $cart->save(); Mage::getSingleton('checkout/session')->setCartWasUpdated(true); ?>
More, potentially arbitrary details: I am using
OneStepCheckout and not Magento's default checkout.