Question

I have a category called Most Purchasing. Here I need to get most purchased/placed products and assign it to specific category programmatically. How can I achieve this?

Note : Here I need to get product collection based on customer purchased/ordered products.

Any help welcome with thanks.

Was it helpful?

Solution

$categoryId = 41; // Your category Id
$category = Mage::getModel('catalog/category')->load($categoryId);
$category->setPostedProducts(array()); // Removes all old products added to your category
$category->save();
$limit = 5; // Number of products to get
$storeId    = Mage::app()->getStore()->getId();
$products = Mage::getResourceModel('reports/product_collection')
            ->addOrderedQty()
            ->addAttributeToSelect('*')
            ->setStoreId($storeId)
            ->addStoreFilter($storeId)
            ->addAttributeToFilter('status', 1)
            ->addAttributeToFilter('visibility', 4)
            ->setOrder('ordered_qty', 'desc')
            ->setPageSize($limit);

Mage::getSingleton('catalog/product_status')->addVisibleFilterToCollection($products);
Mage::getSingleton('catalog/product_visibility')->addVisibleInCatalogFilterToCollection($products);
foreach($products as $product){
    $product->setCategoryIds($categoryId);
    $product->save();
}

OTHER TIPS

I have achieved this by changing some modifications in Jaimin's code. This is the solution :

$bestcategoryId = 19; // Your category Id
$bestcategory = Mage::getModel('catalog/category')->load($bestcategoryId);
$bestcategory->setPostedProducts(array()); // Removes all old products added to your category
$bestcategory->save();

$_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', 'asc');
$categorybest = array($bestcategoryId);
foreach ($_products as $_product){
    $product = Mage::getModel('catalog/product')->load($_product->getId());
    $categoryb = array_merge($categorybest,$product->getCategoryIds());
    $product->setCategoryIds($categoryb);
    $product->save();

}

Thanks for @Jaimin support.

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top