0

I'm working on a code which retrieve Magento best selling products of a category. It works perfectly when a category has products. But the website has multiple category levels. when parent categories not have product it not shows best selling products.

But I need to show child categories best selling products when user in parent categories pages.

function getBestsellingProducts()
{     
    // number of products to display
    $productCount = 10; 

    // store ID
    $storeId    = Mage::app()->getStore()->getId();       
    $categorycf=Mage::registry('current_category');
  echo   $currentCategoryId= $categorycf->getId();


  // $categoryx = Mage::getModel('catalog/category')->load(321);
//   $categoryx2 = Mage::getModel('catalog/category')->load(312);




    // get most viewed products for current category
    $products = Mage::getResourceModel('reports/product_collection')
                    ->addAttributeToSelect('*')        
                    ->addOrderedQty()
                    ->setStoreId($storeId)
                    ->addStoreFilter($storeId)
                    ->addCategoryFilter(Mage::registry('current_category'))
                    //->addCategoryFilter($categoryx2)
                    //->addCategoryFilter($categoryx)
                    ->setOrder('ordered_qty', 'desc')
                    ->setPageSize($productCount);                     

    Mage::getSingleton('catalog/product_status')
            ->addVisibleFilterToCollection($products);
    Mage::getSingleton('catalog/product_visibility')
            ->addVisibleInCatalogFilterToCollection($products);

    return $products; 
}

code for show products

$products = getBestsellingProducts(); 

    foreach ($products as $p) {                     
    $_product = Mage::getModel('catalog/product')->load($p->getId());
    echo $_product->getName();
    }

I notice "addCategoryFilter" function only support for one category. so is there any other way to get best selling products from a child categories of parent category.

  • 1
    Just a quick thought, but I'd say you will first of all have to get all child categories form a catalog_category model into an array and then you could try working with this approach here: magento.stackexchange.com/questions/7094/…. Also, you shouldn't load() products in a foreach ;) – Christoph Farnleitner Jan 24 '18 at 16:20
  • I'm currently tying run individual collection query for each sub category and finally choose top 5 from it, i'm bit unsure about it's performance yet :) – Suneth Kalhara Jan 24 '18 at 16:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.