magento获取商品信息

来源:互联网 发布:全国房地产数据公司 编辑:程序博客网 时间:2024/05/01 21:28

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:

// 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());}?>
原创粉丝点击