How to add Magento 2 Add category programmatically

How to add Magento 2 Add category programmatically

In this post we will show you Magento 2 Add category programmatically, hear for Magento 2 Add category programmatically we will give you demo and example for implement.

we will going to show how to create categories programmatically. It comes in handy when you are trying to import data from APIs, CSV files, XML documents and so on.

code for Magento 2 Add category programmatically

1st, you need to load your data into an array. We will insert the categories one by one using the methods below ::

foreach ($array_with_categories as $val_row) 
{
    $val_data = $this->prepareData($val_row);
    $this->createCategory($val_data);
}

As you can see above, we prepare the data to then create the category afterwards. we personally find it an easier way to manipulate data and it’s quite re-usable.

    /**
     * @param string $row
     * @param int $id
     * @return array mixed
     */
    protected function prepareData($row, $id = null)
    {
          // in case you want to user the root category id
//        $setrootCat = $this->_objectManager->get('Magento\Catalog\Model\Category');
//        $cat_info = $setrootCat->load($rootrowId);
//        $categoryTmp->setPath($setrootCat->getPath());

        $data_val = [
            'data' => 
			[
				"name" => $row["category_name"],
                "parent_id" => 2,                
				"position" => 10,
                "is_active" => true,                
                "include_in_menu" => false,
            ],
            'custom_attributes' => 
			[
                "display_mode"=> "PRODUCTS",
                "is_anchor"=> "1",
//              "url_key"=> "", 
				// if not set magento uses 
				// the name to generate it				
//              "custom_use_parent_settings"=> "0",
//              "custom_apply_to_products"=> "0",
//              "automatic_sorting"=> "0",
//              "url_path"=> "cat2",
//              "my_own_attribute" => "value" 
				// add your attribute
            ]
        ];

        if($id) 
		{
            $data_val['data']['id'] = $id;
        }

        return $data_val;
    }

Once the data is ready, let’s create the new category using the returned data above.

/**
 * @param array $data_val
 * @return bool val
 */
protected function createCategory(array $data_val)
{
    $setcategory = $this->_objectManager
        ->create('Magento\Catalog\Model\Category', $data_val)
        ->setCustomAttributes($data_val['custom_attributes']);

    $setrepository = $this->_objectManager->get(CategoryRepositoryInterface::class);
    $result = $setrepository->save($setcategory);

    echo "Created Category :: " . $data_val['data']['name'] . "\n";

    return true;
}

Now should be able to see it in your Back-end(admin), Products > Categories.

Hope this code and post will helped you for implement Magento 2 Add category programmatically. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve onlincode. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs onlincode.org

Leave a Comment

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

1  +  6  =  

We're accepting well-written guest posts and this is a great opportunity to collaborate : Contact US