Magento 1.9 – Related Products with Same Attribute

magento-1.9product-relations

I am trying to do the same thing in Magento CE 1.9.1.0 . Basically I want to edit the related products block to show all products that have the same value for a specific attribute. Basically I have an attribute called family and when you view product abc which belongs to the attribute family 'Pepsi' I want to display all other products that have a value for the family attribute of 'pepsi'

So I am altering the file app/design/frontend/MY_THEME/default/template/catalog/product/list/related.phtml

The first thing I do in this file is get the value of the family attribute by doing the below

         //get the name of the family that the product being viewed is a part of
         $itemcollectionname = Mage::getModel('catalog/product')->load($_product->getId())->getAttributeText('family');

I then tried using the code in the above post like so

         $rcollection = Mage::getModel('catalog/product')->getCollection()
         ->addAttributeToSelect(Mage::getSingleton('catalog/config')->getProductAttributes()) //add some attribtues to select
         ->addAttributeToFilter('family', array('eq'=>$itemcollectionname);//filter products with the same family
         Mage::getSingleton('catalog/product_status')->addVisibleFilterToCollection($rcollection); //only active products
         Mage::getSingleton('catalog/product_visibility')->addVisibleInCatalogFilterToCollection($rcollection);//only visible products
        $rcollection->setPage(1,5);//limit to 5 products
        echo "$rcollection<br />";

Best Answer

First of all you need to set in Attribute settings "Used in product listing" to Yes.

Then you can simple do:

Avoid double load the product, it is already loaded.

    //$itemcollectionname = Mage::getModel('catalog/product')->load($_product->getId())->getAttributeText('family');
$itemcollectionname = $_product->getAttributeText('family');

Or load a new collection like:

$itemcollectionname = Mage::getResourceModel('catalog/product_collection')->addAttributeToSelect('*');

foreach($itemcollectionname as $product){
   echo $product->getFamily();
   //OR
   echo $product->getAttributeText('family');
}

So if you want to filter by family you will need a value to filter by:

Example:

$itemcollectionname = Mage::getResourceModel('catalog/product_collection')
                        ->addAttributeToSelect('*')
                        ->addAttributeToFilter('family', 'Pants');

    foreach($itemcollectionname as $product){
       echo $product->getId();
    }
Related Topic