0

I use bellow code, which works fine, I'm able to show randomly 5 products from same category on my view page.

I would like to show only products which are in stock. Now it is showing both out of stock and in stock products.

<?php $categories = $_product->getCategoryIds();?> 
        <?php $result = array(); 
        foreach($categories as $cat_id) { 
        $category = Mage::getModel('catalog/category'); 
        $category->load($cat_id); 
        $collection = $category->getProductCollection(); 
        foreach ($collection as $product) { 
        $result[] = $product->getId(); 
        } 
        } 
        ?> 

    <?php if(sizeof($result) >= 5) 
    { 
    $ourneed = array_rand($result,5); 
    foreach($ourneed as $cc) 
    { 
    $thisproduct= Mage::getModel('catalog/product')->load($result[$cc]); 
    ?> 
1

Add in stock filter to your collection.

The following code was tested locally and seems to work fine:

$category = Mage::getModel('catalog/category');
$category->load(250);
$collection = $category->getProductCollection();
Mage::getSingleton('cataloginventory/stock')->addInStockFilterToCollection($collection);

Translating that to your code, which I didn't test gives you:

<?php 

      $categories = $_product->getCategoryIds();

      $result = array(); 

      foreach($categories as $cat_id) { 
         $category = Mage::getModel('catalog/category'); 
         $category->load($cat_id); 
         $collection = $category->getProductCollection();
         Mage::getSingleton('cataloginventory/stock')->addInStockFilterToCollection($collection);

         foreach ($collection as $product) { 
              $result[] = $product->getId(); 
         } 
      } 

      if(sizeof($result) >= 5) { 
          $ourneed = array_rand($result,5); 
          foreach($ourneed as $cc){ 
              $thisproduct= Mage::getModel('catalog/product')->load($result[$cc]); 

             // Provided Code Sample Appears Incomplete
          }
      }
?> 
| 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.