Yet another blog (hopefully a useful one though)
Magento – Show image from a random product in a specific category
A website we developed recently required some boxes on the homepage that link through to a specific category each, and each box needed to show an image from a random product from within that category. If you would like to do the same, here’s how it’s done:
- Create a PHTML file in your template folder, such as app/design/frontend/yourpackage/yourtheme/template/catalog/navigation/box.phtml
- Put this code in the file:
$images = array(); $catId=37; // put your category ID in here $products = Mage::getModel('catalog/product')->getCollection() ->addAttributeToSelect('image') ->addCategoryFilter(Mage::getModel('catalog/category')->load($catId)); Mage::getSingleton('catalog/product_status')->addSaleableFilterToCollection($products); // Only select products that are salable $products->load(); foreach($products as $product){ $images[] = $product->getImageUrl(); } if (sizeof($images) > 1) { $random_image = array_rand($images, 1); } else { $random_image = 0; } echo "<div class='box'><img src='" . $images[$random_image] . "'/></div>";
You can find the ID for your category by logging into the admin area and going to Catalog > Manage Categories and clicking on a category. You should see the ID come up next to the category name in the editable area.
- All you need to do now is specify where the box is shown. Open a layout file, such as app/design/frontend/yourpackage/yourtheme/layout/catalog.xml and use this layout update:
<reference name="left"><!-- change left to any structural block you want to target, such as right or content. --> <block type="catalog/navigation" name="catalog.box" template="catalog/navigation/box.phtml"/> <!--change the template path to wherever you put the template file --> </reference>
And that’s it! You should now have a block that shows an image from a random product within a specific category. You’ll need to do some styling to get it looking right mind but I hope this helps.
Ben
Creative Lead
MS Internet
June 16, 2010 - 2:55 pm
Thanks very good for report, I follow your blog