Get only products in stock on view page
-
13-12-2019 - |
Question
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]);
?>
Solution
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
}
}
?>
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange