Tag Archives: Categories

How to add categories to product by product sku programmatically in Magento

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<?php
$rootDir = ""; //root path
include($rootDir."app/Mage.php");
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
Mage::app("default");
$baseUrl = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB);

// $productsSkus is an array of the products you want to modify.
// Create it however you want, I did it like this...
$productsSkus = array('100246','800649','017261','006403');

//update product categories
for($i=0;$i<count($productsSkus);$i++)
{
$productModel = Mage::getModel('catalog/product');
$productId = $productModel->getIdBySku($productsSkus[$i]);
$product = $productModel->load($productId);
$categoryArr = $product->getCategoryIds();
// Array of category_ids to add.
$categoryArr[] = 842;
$product->setCategoryIds(array($categoryArr));
$product->save();

}
?>

Hope you will enjoy!