Magento – programmatically assign a product collection to a category

magento-1.8magento-1.9magento-community

I would like to programmatically assign a product collection to a category.
This is my product collection for example

$_productCollection = Mage::getModel('catalog/product')
->getCollection()
->joinField('category_id', 'catalog/category_product', 'category_id', 'product_id = entity_id', null, 'left')
->addAttributeToSelect('*')
->addAttributeToFilter('category_id', array(
        array('finset' => '345'),
        array('finset' => '320')
        )
)
->addAttributeToSort('created_at', 'desc');
$_productCollection->getSelect()->group('e.entity_id');

I want these products to be assigned to a category id. Is it possible?

Best Answer

I will add an answer with the help of the above link i posted.

$collection = Mage::getModel('catalog/product')->getCollection();

foreach ($collection as $product_all) {

    $product_id  =  $product_all['entity_id'];//This will give you the product id

    $product    = Mage::getModel('catalog/product');
    $product ->load($product_id);
    $categories = $product->getCategoryIds();


    $categories[] = 152;//HERE YOU CAN ASSIGN WHATEVER CATEGORY ID YOU WANT TO UPDATE

    $product->setCategoryIds($categories);
    $product->save();
}
Related Topic