Programmatically add Magento products to categories

I just want to add that you can remove and add with getSingleton category API:

To Remove product from category:

Mage::getSingleton('catalog/category_api')->removeProduct($category->getId(),$p‌​roduct->getId());

To Add Product to Category:

Mage::getSingleton('catalog/category_api')->assignProduct($category->getId(),$p‌​roduct->getId());

This will not overwrite any categories the product is already in


In PHP code you can put them into the category while you are importing them.

Say you have a product called $product and a category ID called $category_id

You can set the categories which a product belongs to by doing the following

$categories = array($category_id);
$product->setCategoryIds($categories);
$product->save();

If the product already has categories and you'd like to add one more then you can use getCategoryIds() like this:

$categories = $product->getCategoryIds();
$categories[] = $categoryId;
$product->setCategoryIds($categories);
$product->save();

Or, as mentioned by Joshua Peck in the comments, you can use the category_api model to add or remove a product from a category without affecting it's current category assignments:

Mage::getSingleton('catalog/category_api')
  ->assignProduct($category->getId(),$p‌​roduct->getId());

Mage::getSingleton('catalog/category_api')
  ->removeProduct($category->getId(),$p‌​roduct->getId());

You can write a module (which takes time but potentially quicker at importing your data) or you can put something together with the API (less involving of Magento programming but potentially slower at importing your data).

Your starting point of what-you-know-already, how valuable your time is and how often you will need to run the update should determine your choice.

Here is the Magento API documentation for adding products to categories (see example at foot of page):

http://www.magentocommerce.com/wiki/doc/webservices-api/api/catalog_category