Magento 1.9 Upsell – Remain on Product Page with Upsell Add to Cart Button

addtocartmagento-1.9product

I have added an "Add to Cart" button for the upsell items on the product view page, using the following code:

<button type="button" onclick="setLocation('<?php echo $this->helper('checkout/cart')->getAddUrl($_link) ?>')">
  <?php echo $this->__('Add to Cart') ?>
</button>

The problem is that when adding the product to the cart it then redirects to the home page. I have the After Adding a Product Redirect to Shopping Cart option set to No in the checkout configuration.

How do I get it to stay on the same page?

Best Answer

Magento have a function _goBack() at Mage_Checkout_CartController,which is give us the facility to redirect user at any page after successfully Cart from addAction by add an extra parameter( return_url) with add to cart url.

protected function _goBack()
    {
        $returnUrl = $this->getRequest()->getParam('return_url');
      /* Check have value of return_url  */
        if ($returnUrl) {

            if (!$this->_isUrlInternal($returnUrl)) {
                throw new Mage_Exception('External urls redirect to "' . $returnUrl . '" denied!');
            }

            $this->_getSession()->getMessages(true);
      /* then redirect to this page */
            $this->getResponse()->setRedirect($returnUrl);

At _goBack magento have check,current Action have any value for return_url param.If have then it redirect to customer to that page.

For this case,you need send a extra parameter return_url with add to cart url.

Currently,you getting cart url from $this->helper('checkout/cart')->getAddUrl($_link) and parent current page url as return_url value

<button type="button" onclick="setLocation('<?php echo $this->helper('checkout/cart')->getAddUrl($_link).'?return_url= '.Mage::helper('core/url')->getCurrentUrl() ?>')">
  <?php echo $this->__('Add to Cart') ?>
</button
Related Topic