How create a category programatically. With the attributes name, url key, image, path, parent id, is active, description.
And
How to insert data for a new attribute added by InstallDate a category. Ejm.: new attribute -> code
Further to Laor's answer, the following code works on Magento 2.1 and uses:
\Magento\Catalog\Model\CategoryFactory
for create
\Magento\Catalog\Api\CategoryRepositoryInterface
for saving
<?php
use \Magento\Framework\App\Bootstrap;
require '/www/mag2.local/app/bootstrap.php';
$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
### Setting area code
### NOTE: more info http://devdocs.magento.com/guides/v2.1/architecture/archi_perspectives/components/modules/mod_and_areas.html
$state = $objectManager->get('\Magento\Framework\App\State');
$state->setAreaCode('base');
createCategory();
function createCategory() {
global $objectManager;
$category = $objectManager->get('\Magento\Catalog\Model\CategoryFactory')->create();
$category->setName('Computer 3');
$category->setParentId(1); // 1: root category.
$category->setIsActive(true);
$category->setCustomAttributes([
'description' => 'Computer 3 desc',
]);
$objectManager->get('\Magento\Catalog\Api\CategoryRepositoryInterface')->save($category);
}
Use code like this:
$category = $objectManager->create('Magento\Catalog\Model\Category', ['data' =>[
"id" => 5,
"parent_id" => 2,
"name" => "cat2",
"is_active" => true,
"position" => 2,
"include_in_menu" => false,
]);
$category->setCustomAttributes([
"display_mode"=> "PRODUCTS",
"is_anchor"=> "1",
"custom_use_parent_settings"=> "0",
"custom_apply_to_products"=> "0",
"url_key"=> "cat2",
"url_path"=> "cat2",
"automatic_sorting"=> "0",
'new_attribute' => 'value' // <-- your attribute
]);
$repository = $objectManager->get(CategoryRepositoryInterface::class);
$repository->save($category);
I'm looking for creating category programmatically too, Kandy answer looks good but I would have used interface instead of objectmanager :
\Magento\Catalog\Model\CategoryFactory
for create
\Magento\Catalog\Api\CategoryRepositoryInterface
for saving
Moreover you need to remove 'id' or it results in a NoSuchEntityException because of the check at save : https://github.com/magento/magento2/blob/2.0.2/app/code/Magento/Catalog/Model/CategoryRepository.php#L117-L119
Please check given below URL to get your issue resolve.