Magento 1 - Display other products from the same category

Posted on May 05, 2011 | Magento 1

How to setup category related products in Product view :

  1. add the following code somewhere in default\template\catalog\product\view.phtml
  2. Configure the category query according to your catalog by uncommenting the following :
  • // ->setPage(1, 1) : selects only one category
  • // ->addFieldToFilter(‘level’,”3″) : selects only 3rd level categories
  • // ->addFieldToFilter(‘parent_id’,”3″) : select only child categories of no 3
  • // ->setOrder(“level”) : combined by setPage, returns the lowest level category
<?php if ($_product) {
      // get collection of categories this product is associated with
      $categories =$_product->getCategoryCollection()
      //  ->setPage(1, 1)
     //->addFieldToFilter(‘level’,"3")                                     
     //->addFieldToFilter(‘parent_id’,"3")                                 
     ->setOrder("level")
       ->load();
           
    // if the product is associated with any category
    if ($categories->count())
    foreach ($categories as $_category)
    {
      $cur_category = Mage::getModel('catalog/category')->load($_category->getId());
    ?>
<div>
    <h2>Other products from :<?=$cur_category->getName()?></h2>
    </div>
<p> <? $products = Mage::getResourceModel('catalog/product_collection')
 ->addCategoryFilter($_category)
 ->addAttributeToSelect('small_image');
 
 foreach ( $products as $productModel )
 {
 $_product = Mage::getModel('catalog/product')->load($productModel->getId());
 $width=135; $height=135;
 $_imageUrl = $this->helper('catalog/image')->init($productModel, 'small_image')->resize($width, $height);
 ?>
 
</p><div class="product-shop">
       <h5><a href="" title="<?php echo $this->htmlEscape($_product->getName()) ?>">
    <?php echo $this->htmlEscape($_product->getName())?></a></h5>
     
     <img src="" alt="<?=$_imageUrl"> width="<?=$width?>" height="<?=$height?>"/>
    <?php echo $this->getPriceHtml($_product, true) ?>
       <?php if($_product->isSaleable()): ?>
     <?php echo $this->__('Add to Cart') ?>
     <?php else: ?>
      <div class="out-of-stock"><?php echo $this->__('Out of stock') ?></div>
         <?php endif; ?>
         <div class="clear"></div>
          <div class="description">
           <?php echo nl2br($_product->getShortDescription()) ?>
        <a href="" title="<?php echo $this->htmlEscape($_product->getName()) ?>"><small><?php echo $this->__('Learn More') ?></small></a>
                </div>
        </div>
<p> <? } 
 }
 }
 ?></p>

Source: http://www.webmasterbulletin.net/2009/02/magento-product-page-how-to-display-other-products-from-same-category/647