Question

I've to list the best selling products and their category name. For this I'd used

$_storeId = Mage::app()->getStore()->getId();
$_products = Mage::getResourceModel('reports/product_collection')
        ->addOrderedQty()
        ->addAttributeToSelect('*')
        ->addAttributeToFilter('visibility', array(
            Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH,
            Mage_Catalog_Model_Product_Visibility::VISIBILITY_IN_SEARCH
        ))
        ->setOrder('ordered_qty', 'desc');

and for getting individual product:

foreach ($_products as $_product) {
//code need to be added here
}

but I'm not getting any way around to get the category name from $_product.

I've tried

$_product->getCollection()->getCategoryIds();

but my script dies and do not execute further.

Was it helpful?

Solution

This is not technically a product collection of type catalog/product, what you need to do is:

$_storeId = Mage::app()->getStore()->getId();
$_products = Mage::getResourceModel('reports/product_collection')
    ->addOrderedQty()
    ->addAttributeToSelect('*')
    ->addAttributeToFilter('visibility', array(
        Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH,
        Mage_Catalog_Model_Product_Visibility::VISIBILITY_IN_SEARCH
    ))
    ->setOrder('ordered_qty', 'desc');
foreach ($_products as $_product){
    $product = Mage::getModel('catalog/product')->load($_product->getId());
    $category_ids = $product->getCategoryIds();
    foreach ($category_ids as $category_id){
        $category = Mage::getModel('catalog/category')->load($category_id);
        <!-- do what you want to with the category here --> 
    }
}

EDIT: as per comment, to limit the collection size:

$_products = Mage::getResourceModel('reports/product_collection')
    ->addOrderedQty()
    ->addAttributeToSelect('*')
    ->addAttributeToFilter('visibility', array(
        Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH,
        Mage_Catalog_Model_Product_Visibility::VISIBILITY_IN_SEARCH
    ))
    ->setOrder('ordered_qty', 'desc');
$_products->getSelect()->limit(5); //or whatever integer you want
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top