create category programmatically if not exist - magento 2
Consider using the Factory pattern for this instead of the object manager (unless you're putting this function in a factory class itself)
class MyClass
{
protected $storeManager;
protected $categoryFactory;
public function __construct(
\Magento\Store\Model\StoreManagerInterface $storeManager,
\Magento\Catalog\Model\CategoryFactory $categoryFactory
) {
$this->storeManager = $storeManager;
$this->categoryFactory = $categoryFactory;
}
public function fetchOrCreateProductCategory($categoryName)
{
// get the current stores root category
$parentId = $this->storeManager->getStore()->getRootCategoryId();
$parentCategory = $this->categoryFactory->create()->load($parentId);
$category = $this->categoryFactory->create();
$cate = $category->getCollection()
->addAttributeToFilter('name', $categoryName)
->getFirstItem();
if (!$cate->getId()) {
$category->setPath($parentCategory->getPath())
->setParentId($parentId)
->setName($categoryName)
->setIsActive(true);
$category->save();
}
return $category;
}
We need to identify the id of category tree root. Then, we
created an instance of the category, set its path
, parent_id
, name
, etc.
/**
* Id of category tree root
*/
$parentId = \Magento\Catalog\Model\Category::TREE_ROOT_ID;
$parentCategory = $this->_objectManager
->create('Magento\Catalog\Model\Category')
->load($parentId);
$category = $this->_objectManager
->create('Magento\Catalog\Model\Category');
//Check exist category
$cate = $category->getCollection()
->addAttributeToFilter('name','test')
->getFirstItem();
if(!isset($cate->getId())) {
$category->setPath($parentCategory->getPath())
->setParentId($parentId)
->setName('test')
->setIsActive(true);
$category->save();
}