Magento mass-assign products to category

DanCapitanDePlai picture DanCapitanDePlai · May 9, 2012 · Viewed 19k times · Source

As the title says,i need to mass-assign products to a category and from the admin i can only edit one product at a time; i dont know why it just doesnt work to mass add them from the "category products" tab in the category page.
Thats why i need another method that's fast,like using phpMyAdmin or something alike.

Any help?

Thanks in advance!

Answer

nachito picture nachito · May 9, 2012

I created a simple script to do this outside of Magento. Be sure to test this first on a single product and make sure it looks as you'd expect.

// Load Magento
require_once 'path/to/app/Mage.php';
Mage::app();

// $productIds is an array of the products you want to modify.
// Create it however you want, I did it like this...
$productsIds = Mage::getModel('catalog/product')->getCollection()
    ->addAttributeToFilter('sku', array('like' => 'something'))
    ->getAllIds();

// Array of category_ids to add.
$newCategories = array(20);
foreach ($productIds as $id) {
    $product = Mage::getModel('catalog/product')->load($id);
    $product->setCategoryIds(
        array_merge($product->getCategoryIds(), $newCategories)
    );
    $product->save();
}

If you wish to overwrite a product's existing categories, change array_merge(...) to just $newCategories.