Simple Helper class for Previous/Next Products in Magento

Simple Helper class for Previous/Next Products in Magento

One of the common requirements in Magento is to have prev/next product on Product Information page. Development logic there is simple, fetch current product id and take the one before and after that one and now you have previous and next products 🙂 Remember that this will work per category only, since you will get list of products in current category.

So how will next code work?
If you dump next line of code in your catalog/product/view.phtml:

Mage::registry('current_category')->getProductsPosition();

You will get array with keys of product id’s and product positions as values of that current category.

I’m not going to put full module here since you can use this helper in any other module, you just need to call it with right name in your template file.

Here comes the helper class:

<?php
/**
 * INCHOO's FREE EXTENSION DISCLAIMER
 *
 * Please do not edit or add to this file if you wish to upgrade Magento
 * or this extension to newer versions in the future.
 *
 * Inchoo developers (Inchooer's) give their best to conform to
 * "non-obtrusive, best Magento practices" style of coding.
 * However, Inchoo does not guarantee functional accuracy of specific
 * extension behavior. Additionally we take no responsibility for any
 * possible issue(s) resulting from extension usage.
 *
 * We reserve the full right not to provide any kind of support for our free extensions.
 *
 * You are encouraged to report a bug, if you spot any,
 * via sending an email to bugreport@inchoo.net. However we do not guaranty
 * fix will be released in any reasonable time, if ever,
 * or that it will actually fix any issue resulting from it.
 *
 * Thank you for your understanding.
 */
 
/**
 * @category Inchoo
 * @package Inchoo_Catalog
 * @author Vedran Subotic <vedran@inchoo.net>
 * @copyright Inchoo <https://inchoo.net>
 * @license http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
 */
class Inchoo_Catalog_Helper_Data extends Mage_Core_Helper_Abstract
{
	public function getPreviousProduct()
    {
        $prodId = Mage::registry('current_product')->getId();
 
        $catArray = Mage::registry('current_category');
 
        if($catArray){
            $catArray = $catArray->getProductsPosition();
            $keys = array_flip(array_keys($catArray));
            $values = array_keys($catArray);
 
            $productId = $values[$keys[$prodId]-1];
 
            $product = Mage::getModel('catalog/product');
 
            if($productId){
                $product->load($productId);
                return $product->getProductUrl();
            }
            return false;
        }
 
        return false;
 
    }
 
 
    public function getNextProduct()
    {
        $prodId = Mage::registry('current_product')->getId();
 
        $catArray = Mage::registry('current_category');
 
        if($catArray){
            $catArray = $catArray->getProductsPosition();
            $keys = array_flip(array_keys($catArray));
            $values = array_keys($catArray);
 
            $productId = $values[$keys[$prodId]-1];
 
            $product = Mage::getModel('catalog/product');
 
            if($productId){
                $product->load($productId);
                return $product->getProductUrl();
            }
            return false;
        }
 
        return false;
    }
 
}

All you need is to generate new links on product view page:

<?php $_prev = $this->helper('inchoo_catalog')->getPreviousProduct(); ?>
<?php $_next = $this->helper('inchoo_catalog')->getNextProduct(); ?>
 
<?php if($_prev): ?><a class="product-prev" href="<?php echo $_prev;?>"><?php echo $this->__('< Previous')?></a><?php endif; ?>
<?php if($_next): ?><a class="product-next" href="<?php echo $_next;?>"><?php echo $this->__('Next >')?></a><?php endif; ?>

Note: this will not work for all cases in layered navigation, since layered navigation doesn’t work that way and may consist of product collection from different categories.

Enjoy coding!

You made it all the way down here so you must have enjoyed this post! You may also like:

How to connect Google Analytics 4 to Magento 2 Bojan Mareljic
Bojan Mareljic, | 35

How to connect Google Analytics 4 to Magento 2

3 best open-source eCommerce platforms in 2021 Zrinka Antolovic
Zrinka Antolovic, | 7

3 best open-source eCommerce platforms in 2021

eCommerce Returns Management – a simple solution from the Fashion industry Zrinka Antolovic
Zrinka Antolovic, | 12

eCommerce Returns Management – a simple solution from the Fashion industry

10 comments

  1. 
    /** where
    * \Magento\Catalog\Model\Category $categoryProduct
    * \Magento\Catalog\Model\ProductRepository $productRepository,
    */
    
    
    	private function getProductPosition(int $productId, int $categoryId)
    	{
    		try {
    			$category = $this->categoryProduct->load($categoryId);
    			$catArray = $category->getProductsPosition();
    			$keys = array_flip(array_keys($catArray));
    			$values = array_keys($catArray);
    
    			if (isset($values[$keys[$productId]]) && current([$keys[$productId]]) > 0) {
    				$productIdPrev = $values[$keys[$productId] - 1];
    				$productPrev = $this->productRepository->getById($productIdPrev);
    				$previous = $productPrev->getProductUrl();
    			}
    
    			if (isset($values[$keys[$productId]]) && $productId productRepository->getById($productIdNext);
    				$next = $productNext->getProductUrl();
    			}
    
                          return [
    				'previous' => $previous,
    				'next'     => $next,
    			];
    
    
    		} catch (\Exception $e) {
    			$this->logger->error('cannot getProductPosition', [$e->getMessage()]);
    		}
    return [];
    	}
  2. This code works but need improvement. It gives back url to an product that is not visible individually.

  3. I also got an error in Magento 1.9.0.1 and PHP7 on the line:

    $productId = $values[$keys[$prodId]-1];

    I replaced it with:

    if($keys[$prodId] != 0):
    $productId = $values[$keys[$prodId]-1];
    $product = Mage::getModel(‘catalog/product’);

    if($productId){
    $product->load($productId);
    return $product->getProductUrl();
    }
    endif;

  4. Big problem in product page :
    Call to undefined method Mage_Catalog_Model_Resource_Category_Flat::getProductsPosition()

  5. Hello,

    I’m newbe in magento.
    I installed magento locally, and have it in portuguese and english. How can I edit the “Next Product” and “Previous Product” to show the portuguese text on the portuguese view?

    Thank you very much,

    Anselmo

  6. I am getting this error can you tell me how to fix that

    tal error: Call to a member function getProductsPosition()

    app\code\community\Inchoo\Prevnext\Helper\Data.php on line 43

  7. Hello,
    it’s a useful code, thank you!

    But there is a little typo in:
    public function getNextProduct()

    The line:
    $productId = $values[$keys[$prodId]-1];
    has to be replaced by:
    $productId = $values[$keys[$prodId]+1];

    BR

    1. Thank you Zuiko for fixing this……..

      Yes…. there is a little typo in:
      public function getNextProduct()
      The line:
      $productId = $values[$keys[$prodId]-1];
      has to be replaced by:
      $productId = $values[$keys[$prodId]+1];

      thanks!
      Nithin

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <blockquote cite=""> <code> <del datetime=""> <em> <s> <strike> <strong>. You may use following syntax for source code: <pre><code>$current = "Inchoo";</code></pre>.

Tell us about your project

Drop us a line. We'd love to know more about your project.