How do I get two products that were added just before current product and two products that were added just after the current product in a same category as the related product?

Here is how I am fetching 4 related products from the same category in product view page. Right now it shows them in random order.

if ($_product) {
    $categories = $_product->getCategoryCollection()
        ->setPage(1, 1)
    if ($categories->count()) { ?>
        <h2>Related Products:</h2>
        <?php foreach ($categories as $_category) {
            $cur_category = Mage::getModel('catalog/category')->load($_category->getId());
            <?php $products = Mage::getResourceModel('catalog/product_collection')

            foreach ($products as $productModel) {
                $_product = Mage::getModel('catalog/product')->load($productModel->getId());
                $width = 200;
                $height = 150;
                $_imageUrl = $this->helper('catalog/image')->init($productModel, 'small_image')->resize($width, $height);
                <div class="related-item">
                    <a href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $this->stripTags($this->getImageLabel($_product, 'small_image'), null, true) ?>">
                        <img src="<?php echo $this->helper('catalog/image')->init($_product, 'small_image')->resize(200, 100); ?>" width="200" height="150" alt="<?php echo $this->stripTags($this->getImageLabel($_product, 'small_image'), null, true) ?>"/>
                    <h4><a href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $this->htmlEscape($_product->getName()) ?>"><?php echo $this->htmlEscape($_product->getName()) ?></a></h4>
            <?php }
        } ?>
    <?php }


  • Related products are already available as selection in magneto for each products. use that functionality. – Minesh Patel Aug 26 '17 at 12:52
  • how you define added just before and added just after ? by date ? by id – Minesh Patel Aug 26 '17 at 12:55
  • if you have both upper and lower limit for above criteria you can do with taking 2 separate collection with limit of 2 for each. and marge both collection to one. – Minesh Patel Aug 26 '17 at 12:56

This should be logically implemented like below

  • Find category of current product
  • Get 2 products of category whose ID is greater than current product ID
  • Get 2 products of category whose ID is lower than current product ID

The code implementation of this should be quick. Give it a try.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.