How to create new categories and assigned products to category programmatically magento

This tutorial I am explaining how to create new category and assigned the existing products to that categories programmatically based on the attribute.

Using this program I am creating new category named ‘manufacturer‘ under the root category and two subcategories ‘manufacturer1‘ and ‘manufacturer2‘ as shown below and assigning the products to that category.

new magento category

Step by step explanation :

1) Create new category
2) Retrieve the attribute (manufacturer)Id
3) Get all the products based on that arttribute (manufacturer)
4) Assign the products to the new category

Create new category

For creating the new categories as the first step I create an array as shown below.

$manufacturers = array(
    0 => 'Manufacturers', // root category
    1 => 'Manufacturer 1', // subcategory
    2 => 'Manufacturer 2' // subcatgeory

);

Then pass this array as a parameter to the addManufacturers() function and create the categories programmatically as shown below.

function addManufacturers( $manufacturers ) {
    Mage::register('isSecureArea', 1);
    $parentId = '2';
    $list = array();

    foreach ($manufacturers as  $key => $manufacturer) {
        try {

            $enabled = 1;
            if ($key == 0) {
                $parentId = '2';
            }
            else {
                $parentId = $list[0];
            }

            $category = Mage::getModel('catalog/category');
            $category->setName($manufacturer);
            $category->setMetaTitle($manufacturer);
            $category->setIncludeInMenu(1);
            $category->setUrlKey(strtolower($manufacturer));
            $category->setDescription(strip_tags($manufacturer));
            $category->setMetaDescription($manufacturer);
            $category->setMetaKeywords($manufacturer);
            $category->setIsActive($enabled);
            $category->setDisplayMode('PRODUCTS');
            $category->setIsAnchor(1); //for active anchor
            $category->setStoreId(Mage::app()->getStore()->getId());
            $parentCategory = Mage::getModel('catalog/category')->load($parentId);
            $category->setPath($parentCategory->getPath());
            $category->setCustomUseParentSettings(true);
            $category->save();
            $list[$key] = $category->getId();
            echo 'Category ' . $category->getName() . ' ' . $category->getId() . ' imported successfully' . PHP_EOL;
        } catch (Exception $e) {
            echo 'Something failed for category ' . $manufacturer . PHP_EOL;
            print_r($e);
        }
    }
    return $list;
}

As the next step we need to get the attribute id (manufacturer) and retrieve all the products based on the particular manufacturer attribute .

Get the attribute Id

$attrLabel = 'manufacturer';
$attr = $product->getResource()->getAttribute($attrLabel);
$manufacturer_id = $attr->getSource()->getOptionId($manufacturer);

Get all the products based on the attribute Id

$newproducts = $product->getCollection()->addAttributeToFilter(array(array('attribute'=>'manufacturer', 'eq'=> $manufacturer_id)));

Then loop through each product and assign the products to the category.

Assign products to the category

$newCategory = array( $list[0] , $list[$key]); // create an array using root and subcategory id
foreach($newproducts as $prod)
{
    $prod->setCategoryIds(
            array_merge($prod->getCategoryIds(), $newCategory)
         );
    $prod->save();
}

Full Code

function assignProductsToCategory($manufacturers ,$list ) {

    $product = Mage::getModel('catalog/product');

    foreach($manufacturers as $key => $manufacturer) {
        if($key == 0) continue;
        $attrLabel = 'manufacturer';
        $attr = $product->getResource()->getAttribute($attrLabel);
        $manufacturer_id = $attr->getSource()->getOptionId($manufacturer);
        echo 'Manufatcurer Name - '.$manufacturer.' '.$manufacturer_id. PHP_EOL;
      
        $newproducts = $product->getCollection()->addAttributeToFilter(array(
            array('attribute'=>'manufacturer', 'eq'=> $manufacturer_id)));
        
        $newCategory = array( $list[0] , $list[$key]);
       
        foreach($newproducts as $prod)
        {
            $product->load($prod->getId());      
            $name = $manufacturer.' '.$product->getName();
            $prod->setName($name);
            echo $name. PHP_EOL;
            $prod->setCategoryIds(
                    array_merge($prod->getCategoryIds(), $newCategory)
                 );
            $prod->save();
        }
     
    }
}

If you have any further queries please leave a reply.
Thanks

Share this Tutorial

Leave a Reply

Your email address will not be published. Required fields are marked *

*