Magento – Filter a product block collection by custom attribute

magento-1.9product-attribute

I extended Mage_Catalog_Block_Product_List's _getProductCollection() previously to return 6 random products to display on the home page. This code was working fine.

$this->setCategoryId(40);
$category = new Mage_Catalog_Model_Category();
$category->load($this->getCategoryId());
$collection = $category->getProductCollection();
$collection->getSelect()->order('rand()');
$collection->getSelect()->limit(6);
$collection->addStoreFilter();

Mage::getModel('catalog/layer')->prepareProductCollection($collection);
$collection->load();

I added a custom product attribute and updated the code to:

$collection = Mage::getModel('catalog/category')->load(4)
    ->getProductCollection()
    ->addAttributeToSelect('*')
    ->addAttributeToFilter('cc_featured', array('eq' => true));
$collection->getSelect()->limit(6);
$collection->addStoreFilter();

Where 4 is my root category. However this returns no results. I debugged the SQL and the problem appears to be this condition cat_index.is_parent=1.

I am not sure if I am going about this right and need some guidance. I have tried answers to similar questions, at best it will find 6 products, but it is missing all the product detail (price, image, etc)

Best Answer

As clarified by comment, this code should retrieve a site-wide product collection of 6 random enable products with filter visibility = 4 (Catalog & Search) and cc_featured = 1.

$collection = Mage::getModel('catalog/product')
    ->getCollection()
    ->addAttributeToSelect('*')
    ->addAttributeToFilter('status',1)
    ->addAttributeToFilter('visibility',4)
    ->addAttributeToFilter('cc_featured',1);
$collection->getSelect()->order(new Zend_Db_Expr('RAND()'))->limit(6);

Note

  • Status = 1 to not load disabled products
  • Visbility = 4 to not load products are not visible individually (e.g. simple products that belong to configurable ones)
  • You don't have to extend the Mage_Catalog_Block_Product_List for this to work, extending Mage_Core_Block_Template would be sufficient.
Related Topic