Reputation: 846
BElow is the function that selects related product of a single product. I wanted it to work in such a way that if there are no related products other random products will be added to the array. Random could be other products of the same category and if there is no procut in the same category we could fetch from other categories.
protected function _prepareData()
{
$product = Mage::registry('product');
/* @var $product Mage_Catalog_Model_Product */
$this->_itemCollection = $product->getRelatedProductCollection()
->addAttributeToSelect('required_options')
->addAttributeToSort('position', Varien_Db_Select::SQL_ASC)
->addStoreFilter()
;
if (Mage::helper('catalog')->isModuleEnabled('Mage_Checkout')) {
Mage::getResourceSingleton('checkout/cart')->addExcludeProductFilter($this->_itemCollection,
Mage::getSingleton('checkout/session')->getQuoteId()
);
$this->_addProductAttributesAndPrices($this->_itemCollection);
}
// Mage::getSingleton('catalog/product_status')->addSaleableFilterToCollection($this->_itemCollection);
Mage::getSingleton('catalog/product_visibility')->addVisibleInCatalogFilterToCollection($this->_itemCollection);
$this->_itemCollection->load();
foreach ($this->_itemCollection as $product) {
$product->setDoNotUseCategoryId(true);
}
return $this;
}
Thanks Abnab
Upvotes: 0
Views: 745
Reputation: 7035
You can use count() to see if there are any related products. If there aren't, then you can load a new product collection with whatever filters you want. As an example, I have filtered below by category_id. I recommend reading up on Magento collections (or here).
protected function _prepareData()
{
...
$this->_itemCollection->load();
// If there are no related products, find more products in same category.
if (count($this->_itemCollection) < 1) {
$this->_itemCollection = Mage::getModel('catalog/product')->getCollection()
->addAttributeToSelect('required_options')
->addAttributeToFilter('category_id', $product->getCategoryId());
}
foreach ($this->_itemCollection as $product) {
...
Upvotes: 1