I was recently working on a site where a “featured” product was required on the homepage. Rather than just making this a category, or a specific product, I wanted to give as much flexibilty as possible, and also allow them some extra functionality.
So, I created a new attribute, “homepage_product” – a boolean. This attribute can be assigned to any product. So, what if there are 10 products selected? I only have room for one. I needed to get a random product from the list of products that had this attribute selected.
I guess I could have read all the products into an array, and then used rand() to grab a random product from that array, but that seemed to provide an over-head, and seemed too complicated for something that should surely be able to be done in Magento.
So, I came up with this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
// get products tagged with homepage_product $collection = Mage::getModel('catalog/product')->getCollection() ->addFieldToFilter(array( array('attribute'=>'homepage_product','eq'=>'1'), )) ->addStoreFilter(); $collection->getSelect()->order(new Zend_Db_Expr('RAND()')); $numProducts = 1; $collection->setPage(1, $numProducts)->load(); foreach($collection as $homepageProduct) { $homepageProductInformation = Mage::getModel('catalog/product')->load($homepageProduct->getEntityId()); } ?> |
Image Credit: NASA's Marshall Space Flight Center
Comment or tweet @douglasradburn