One of my magento project needed to show top selling products under specific category. I didn’t find any available function for it by calling magento category model and finally figured out a solution programmatically. Let me go ahead and share the codes with you all, hope you might find it helpful
<?php
$connection = Mage::getSingleton('core/resource')->getConnection('core_write');
$attribute_set_id = 4;
$store_id = Mage::app()->getStore()->getId();
$currentcategory = Mage::registry('current_category');
$category_number = $currentcategory->getId(); //The number of the category you want to load
$ts_sql = "SELECT * FROM `sales_flat_order_item` as `order_items` INNER JOIN sales_flat_order as `order` ON `order`.entity_id = order_items.order_id AND `order`.state <> 'canceled' LEFT JOIN catalog_product_entity as e ON e.entity_id = order_items.product_id AND e.entity_type_id = '".$attribute_set_id."' INNER JOIN catalog_category_product_index as cat_index ON cat_index.product_id=e.entity_id AND cat_index.store_id='".$store_id."' AND cat_index.category_id='".$category_number."' AND cat_index.is_parent=1 WHERE (parent_item_id IS NULL) GROUP BY order_items.product_id HAVING (SUM(order_items.qty_ordered) > 0) ORDER BY order_items.product_id DESC";
$ts_query = $connection->query($ts_sql);
while($ts_product=$ts_query->fetch()){
$_product = Mage::getModel('catalog/product')->load($ts_product['product_id']);
if($_product->getVisibility()!=1 && $_product->getStatus()==1){
?>
<a href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $this->stripTags($this->getImageLabel($_product, 'small_image'), null, true) ?>" class="product-image"><img src="<?php echo $this->helper('catalog/image')->init($_product, 'small_image')->resize(250, 207); ?>" width="250" height="207" alt="<?php echo $this->stripTags($this->getImageLabel($_product, 'small_image'), null, true) ?>" /></a>
<h2 class="product-name">a href="<?php echo $this->stripTags($_product->getProductUrl()) ?>" title="<?php echo $this->stripTags($_product->getName(), null, true) ?>"> <?php echo $_product->getName(); ?></a></h2>
<?php
}
}
?>
I would like to know your thoughts, please feel free to share your comments and suggestions.
Thank you !