How to assign categories for products in magento Programmatically

Faran Khan picture Faran Khan · Jul 3, 2014 · Viewed 9.2k times · Source

I am a newbie in magento. Basically, I want to assign multiple products to multiple categories. I have followed this post and I have done the following code which is working fine:

   $collection = Mage::getModel('catalog/product')->getCollection();//my coustom collection
        $categorys_ids = array(1,2,3,4,5);//Array of ids etc 
        if ($categorys_ids != NULL && $collection->getData()!= NULL)
            {
                foreach ($collection as $product) 
                {
                        $categories_pd = $product->getCategoryIds();                              
                        $product->setCategoryIds(array_merge($product->getCategoryIds(),array($categorys_ids)));
                        $product->save();
                }
            }

Now, the main issue is that when I assign set category id for the products it takes a lot of time. I have 200 products and this takes up to two minutes or so, which is a lot of time.

I was wondering if there is a way that I can assign categories to a products array instead of assigning products to categories or something that can be optimized and take less time.

Answer

Marius picture Marius · Jul 3, 2014

Here is how you can assign multiple products to a category and merge with the existing products.
The example is for one category but you can turn it into a loop to make it work for more.

$categoryId = 6; 
$category = Mage::getModel('catalog/category')->setStoreId(Mage_Core_Model_App::ADMIN_STORE_ID)->load($categoryId);
//get the current products
$products = $category->getProductsPosition();
//now attach the other products.
$newProductIds = array(1,2,3,4,5);
foreach ($newProductIds as $id){
    $products[$id] = 1;//you can put any other position number instead of 1.
}
//attach all the products to the category
$category->setPostedProducts($products);
//save the category.
$category->save();

If you want an even faster way of doing it you can do direct inserts in the table catalog_category_product.
Just make sure you reindex when you are done.