1

I'm trying to display related products in the product view page. I created a collection of them but when i try to fetch them, the getName() method renders the correct name but getProductUrl() renders the url of the parent product. Here is my code:

  $categoryId = array_shift($_product->getCategoryIds());
  $related_prods = Mage::getModel('catalog/product')
                ->getCollection()
                ->addAttributeToSelect('*')
                ->addUrlRewrite($categoryId)
                ->addAttributeToFilter('entity_id',array('in'=>$_product->getRelatedProductIds()))->load();
  <div>
  <?php foreach($related_prods as $related){ ?>
  <a href="<?php  $this->getUrl('books').$related->getUrlPath()."<br />";?>"><?php echo $related->getName();?></a>
  <?php } ?>
  </div>

Thanks in advance.

0

you have to load the product to get product url

 $categoryId = array_shift($_product->getCategoryIds());
      $related_prods = Mage::getModel('catalog/product')
                    ->getCollection()
                    ->addAttributeToSelect('*')
                    ->addUrlRewrite($categoryId)
                    ->addAttributeToFilter('entity_id',array('in'=>$_product->getRelatedProductIds()))->load();
      <div>
      <?php foreach($related_prods as $related){ 
    $related=Mage::getModel('catalog/product')->load($related->getId());
    ?>
      <a href="<?php  echo $this->getUrl('books').$related->getUrlPath()."<br />";?>"><?php echo $related->getName();?></a>
      <?php } ?>
      </div>
  • I have another question: I want to move this code from my product (view.phtml) and call it from model/helper(?). What is the best approach and how to call my function inside view.phtml ? – mockingbid Nov 12 '15 at 10:59
  • did you create a module for that? add this function in your helper and get the collection Mage::helper('book')->urfunction(); – Qaisar Satti Nov 12 '15 at 11:02
  • No, i was thinking of using the catalog module, i'm just testing in a sample-data installation to get a sense of it. – mockingbid Nov 12 '15 at 11:06
  • then don't change in core module. that my suggestion for testing purpose get collection in view directly. – Qaisar Satti Nov 12 '15 at 11:08
  • copy model file in from code/mage to core/local and make changes there it is best approach. – Qaisar Satti Nov 12 '15 at 11:09
1

you forgot an echo in this line:

<a href="<?php  $this->getUrl('books').$related->getUrlPath()."<br />";?>"><?php echo $related->getName();?></a>

it should be

<a href="<?php echo $this->getUrl('books').$related->getUrlPath()."<br />";?>"><?php echo $related->getName();?></a>

Side note... you should not generate the url like this <?php echo $this->getUrl('books').$related->getUrlPath()."<br />"

use $related->getProductUrl()

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.