Here, I will show you the code to get the most viewed products in Magento. The function addViewsCount() filters the products with their views count.
Here is the code:-
Get overall Most viewed products
public function getMostViewedProducts()
{
/**
* Number of products to display
* You may change it to your desired value
*/
$productCount = 5;
/**
* Get Store ID
*/
$storeId = Mage::app()->getStore()->getId();
/**
* Get most viewed product collection
*/
$products = Mage::getResourceModel('reports/product_collection')
->addAttributeToSelect('*')
->setStoreId($storeId)
->addStoreFilter($storeId)
->addViewsCount()
->setPageSize($productCount);
Mage::getSingleton('catalog/product_status')
->addVisibleFilterToCollection($products);
Mage::getSingleton('catalog/product_visibility')
->addVisibleInCatalogFilterToCollection($products);
return $products;
}
Get Most viewed products for current category
public function getMostViewedProducts()
{
// number of products to display
$productCount = 5;
// store ID
$storeId = Mage::app()->getStore()->getId();
// get most viewed products for current category
$products = Mage::getResourceModel('reports/product_collection')
->addAttributeToSelect('*')
->setStoreId($storeId)
->addStoreFilter($storeId)
->addViewsCount()
->addCategoryFilter(Mage::registry('current_category'))
->setPageSize($productCount);
Mage::getSingleton('catalog/product_status')
->addVisibleFilterToCollection($products);
Mage::getSingleton('catalog/product_visibility')
->addVisibleInCatalogFilterToCollection($products);
return $products;
}
Get Most viewed products for last 30 days
public function getMostViewedProducts()
{
// number of products to display
$productCount = 5;
// store ID
$storeId = Mage::app()->getStore()->getId();
// get today and last 30 days time
$today = time();
$last = $today - (60*60*24*30);
$from = date("Y-m-d", $last);
$to = date("Y-m-d", $today);
// get most viewed products for last 30 days
$products = Mage::getResourceModel('reports/product_collection')
->addAttributeToSelect('*')
->setStoreId($storeId)
->addStoreFilter($storeId)
->addViewsCount()
->addViewsCount($from, $to)
->setPageSize($productCount);
Mage::getSingleton('catalog/product_status')
->addVisibleFilterToCollection($products);
Mage::getSingleton('catalog/product_visibility')
->addVisibleInCatalogFilterToCollection($products);
return $products;
}
Hope this helps. Thanks.