Magento 1.9- Display Most Viewed Products

Create a file app/code/local/Mage/Catalog/Block/Product/Mostviewed.php and add the following lines of code in it.

 
class Mage_Catalog_Block_Product_Mostviewed extends Mage_Catalog_Block_Product_Abstract{
    public function __construct(){
        parent::__construct();
        $storeId    = Mage::app()->getStore()->getId();
        $products = Mage::getResourceModel('reports/product_collection')
            ->addOrderedQty()
            ->addAttributeToSelect('*')
            ->addAttributeToSelect(array('name', 'price', 'small_image'))
            ->setStoreId($storeId)
            ->addStoreFilter($storeId)
            ->addViewsCount();
        Mage::getSingleton('catalog/product_status')->addVisibleFilterToCollection($products);
        Mage::getSingleton('catalog/product_visibility')->addVisibleInCatalogFilterToCollection($products);

        $products->setPageSize(5)->setCurPage(1);
        $this->setProductCollection($products);
    }
}
Step 2:

Create a file app/design/frontend/default/YourTheme/template/catalog/product/mostviewed.phtml and add the following lines of code in it.

 
<?php if (($_products = $this->getProductCollection()) && $_products->getSize()): ?>
<?php echo $this->__('These Products Are Popular Right Now!') ?>
<?php $_collectionSize = 5;//count($_products->getItems()); echo $_collectionSize; ?>
    <?php $i=1; foreach ($_products->getItems() as $_product): ?>
  • <?php echo $this->htmlEscape($this->getImageLabel($_product, 'small_image')) ?>

    <?php echo $this->htmlEscape($_product->getName()) ?>

    <?php if($_product->getRatingSummary()): ?> <?php echo $this->getReviewsSummaryHtml($_product, 'short') ?> <?php endif; ?> <?php echo $this->getPriceHtml($_product, true) ?> <?php if($_product->isSaleable()): ?>
    <?php else: ?>

    <?php echo $this->__('Out of stock') ?>

    <?php endif; ?>
  • <?php $i++; endforeach; $kol = $_collectionSize; ?>
<?php endif; ?>
Step 3:

Now, we have the code in place which will fetch the most viewed products on call. Still, we need to add a block to show most viewed products in a desired location.

 
{{block type="catalog/product_mostviewed" template="catalog/product/mostviewed.phtml"}}

No comments:

Post a Comment