Showing posts with label assign products to categories. Show all posts
Showing posts with label assign products to categories. Show all posts

Programmatically Assign Products from one category to other category in Magento


Programmatically Assign Products from one category to other category in Magento

Create a PHP script file in root directory of Magento directory structure and put below code in it.
Adjust category from ID and to ID according to need.
Execute script.
 To
//  5 => 10
$from = 5;
$to = 10;
 
$category = Mage::getModel('catalog/category')->load($from); 
 
$productCollection = $category->setStoreId(1)->getProductCollection();
 
foreach($productCollection as $_product) {
  $product = Mage::getModel('catalog/product')->load($_product->getId());
 
  $newCategories = $origCats = $product->getCategoryIds();
  if(!in_array($to, $origCats)) {
    $newCategories = array_merge($origCats, array($to));
    $product->setCategoryIds($newCategories)->save();
    echo 'Assigned -- ' . $product->getId() . '
'; } } echo 'Completed Execution!!!'; ?>