Magento – create categories and sub categories programmatically in magento2
categorymagento2PHP
How to create categories and sub categories programmatically in magento2?
Please anyone knows then explain me.
Best Answer
use following code to create category and subcategory. just make slight changes as per your requirement and use it where you want to create categories and sub categories
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
//you should prefer to use dependency injection here
$cats = [
"cat1","cat2"
];
$parent_id = 322; // category id of parent
foreach($cats as $cat) {
$data = [
'data' => [
"parent_id" => $parent_id,
'name' => $cat,
"is_active" => true,
"position" => 10,
"include_in_menu" => false,
]
];
$category = $objectManager ->create('Magento\Catalog\Model\Category', $data);
$repository = $objectManager->get(\Magento\Catalog\Api\CategoryRepositoryInterface::class);
$result = $repository->save($category);
}
According to Matt Cutts, duplicate categorization will not hurt you unless the content itself or the violation is egregious and done only for SEO value. In the example that you set forth above it does not seem to be too over the top, but if you had hundreds of categories with all of the same products in it, using the categorization to bolster your page count, you may be in trouble.
In short: You should organize your catalog to appeal to a human using the site, not for Google to index you. If you follow this simple guideline you should be in good shape.
As an aside:
Consult an SEO professional if you have questions about what is acceptable and what is not -- SEO questions are not on-topic in this forum - Magento site administration and programming questions are encouraged.
Best Answer
use following code to create category and subcategory. just make slight changes as per your requirement and use it where you want to create categories and sub categories
credits: http://www.zexperto.com/magento2x/create-category-magento2-programmatically