cancel
Showing results for 
Search instead for 
Did you mean: 

How to insert category programmatically in magento 2.3?

SOLVED
   Did you know you can see the translated content as per your choice?

Translation is in progress. Please check again after few minutes.

How to insert category programmatically in magento 2.3?

Hi Folks,

 

I am going to import the products from the .xml file and I need category inserted as programmatically in magento 2.3 

 

My code is working fine with attributes, description, price etc but it not importing category. I think the issue with below function.


$category->save();


Anybody can help me to solve this issue?

 

Thanks in Advance

1 ACCEPTED SOLUTION

Accepted Solutions

Re: How to insert category programmatically in magento 2.3?

Hi Vimal,

Thank you for your quick feedback. I have try to use your code but it is not work for me. Here I am going to show you my code. So, Can you please help me where I do mistake? Here are my code.

 

<?php  use Magento\Framework\App\Bootstrap;

class sk_scripts {	
	var $obj;
	var $imageDir;
	var $productManager;
	
	public function __construct() {
		$rootDirectoryPath = '../';
		require $rootDirectoryPath . '/app/bootstrap.php';
		
		$params = $_SERVER;
		$bootstrap = Bootstrap::create(BP, $params);
		$this->obj = $bootstrap->getObjectManager();		
		$state = $this->obj->get('Magento\Framework\App\State');
		$state->setAreaCode('adminhtml');
		
		$storeManager = $this->obj->get('\Magento\Store\Model\StoreManagerInterface');
		
		$store = $storeManager->getStore();
		$this->storeId = $store->getStoreId();
		//$this->rootNodeId = $store->getRootCategoryId();
		$this->productManager = $this->obj->get('\Magento\Catalog\Api\Data\ProductInterface');
			
	}	
	
	public function save_product($catalog_arr) {
		$category_name = 'LCD Monitor';
		if($category_name!="") {
			$cateId = $this->save_category($category_name);
			
		}		
	}	
	
	public function save_category($CategoryName=NULL) {
		if($CategoryName!=NULL) {
			//$parentId = \Magento\Catalog\Model\Category::TREE_ROOT_ID; //This will return value 1
			$parentId = 2; // We have set parent category as a DEFAULT CATEGORY
			$parentCategory = $this->obj->create('Magento\Catalog\Model\Category')->load($parentId);
			$category = $this->obj->create('Magento\Catalog\Model\Category');
			
			//Check exist category
			$cate = $category->getCollection()
				->addAttributeToFilter('name',$CategoryName)
				->getFirstItem();

			if($cate->getId()==NULL) {
				$category->setPath($parentCategory->getPath())
					->setParentId($parentId)
					->setName($CategoryName)
					->setIsActive(true);
				$category->save();
				return $category->getId();
			} else {
				return $cate->getId();
			}		
		} else {
			return "Please enter valid category name.";
		}		
	}				
}	
$my_script = new sk_scripts();
$my_script->save_product();

Thank you in advance.

View solution in original post

3 REPLIES 3

Re: How to insert category programmatically in magento 2.3?

HI @m2expdeveloper 

You can create category programmatically using below code.  or you can compare you code with it. 

use \Magento\Framework\App\Bootstrap;

include('../app/bootstrap.php');
$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
$url = \Magento\Framework\App\ObjectManager::getInstance();
$storeManager = $url->get('\Magento\Store\Model\StoreManagerInterface');
$mediaurl= $storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);
$state = $objectManager->get('\Magento\Framework\App\State');
$state->setAreaCode('frontend');
/// Get Website ID
$websiteId = $storeManager->getWebsite()->getWebsiteId();
echo 'websiteId: '.$websiteId." ";

/// Get Store ID
$store = $storeManager->getStore();
$storeId = $store->getStoreId();
echo 'storeId: '.$storeId." ";

/// Get Root Category ID
$rootNodeId = $store->getRootCategoryId();
echo 'rootNodeId: '.$rootNodeId." ";
/// Get Root Category
$rootCat = $objectManager->get('Magento\Catalog\Model\Category');
$cat_info = $rootCat->load($rootNodeId);

$categorys=array('Levis','Wranglers','Basics'); // Category Names
foreach($categorys as $cat)
{

$name=ucfirst($cat);
$url=strtolower($cat);
$cleanurl = trim(preg_replace('/ +/', '', preg_replace('/[^A-Za-z0-9 ]/', '', urldecode(html_entity_decode(strip_tags($url))))));
$categoryFactory=$objectManager->get('\Magento\Catalog\Model\CategoryFactory');
/// Add a new sub category under root category
$categoryTmp = $categoryFactory->create();
$categoryTmp->setName($name);
$categoryTmp->setIsActive(true);
$categoryTmp->setUrlKey($cleanurl);
$categoryTmp->setData('description', 'description');
$categoryTmp->setParentId($rootCat->getId());
$mediaAttribute = array ('image', 'small_image', 'thumbnail');
$categoryTmp->setImage('/m2.png', $mediaAttribute, true, false);// Path pub/meida/catalog/category/m2.png
$categoryTmp->setStoreId($storeId);
$categoryTmp->setPath($rootCat->getPath());
$categoryTmp->save();
}


I hope it will help you!
 

Re: How to insert category programmatically in magento 2.3?

Hi Vimal,

Thank you for your quick feedback. I have try to use your code but it is not work for me. Here I am going to show you my code. So, Can you please help me where I do mistake? Here are my code.

 

<?php  use Magento\Framework\App\Bootstrap;

class sk_scripts {	
	var $obj;
	var $imageDir;
	var $productManager;
	
	public function __construct() {
		$rootDirectoryPath = '../';
		require $rootDirectoryPath . '/app/bootstrap.php';
		
		$params = $_SERVER;
		$bootstrap = Bootstrap::create(BP, $params);
		$this->obj = $bootstrap->getObjectManager();		
		$state = $this->obj->get('Magento\Framework\App\State');
		$state->setAreaCode('adminhtml');
		
		$storeManager = $this->obj->get('\Magento\Store\Model\StoreManagerInterface');
		
		$store = $storeManager->getStore();
		$this->storeId = $store->getStoreId();
		//$this->rootNodeId = $store->getRootCategoryId();
		$this->productManager = $this->obj->get('\Magento\Catalog\Api\Data\ProductInterface');
			
	}	
	
	public function save_product($catalog_arr) {
		$category_name = 'LCD Monitor';
		if($category_name!="") {
			$cateId = $this->save_category($category_name);
			
		}		
	}	
	
	public function save_category($CategoryName=NULL) {
		if($CategoryName!=NULL) {
			//$parentId = \Magento\Catalog\Model\Category::TREE_ROOT_ID; //This will return value 1
			$parentId = 2; // We have set parent category as a DEFAULT CATEGORY
			$parentCategory = $this->obj->create('Magento\Catalog\Model\Category')->load($parentId);
			$category = $this->obj->create('Magento\Catalog\Model\Category');
			
			//Check exist category
			$cate = $category->getCollection()
				->addAttributeToFilter('name',$CategoryName)
				->getFirstItem();

			if($cate->getId()==NULL) {
				$category->setPath($parentCategory->getPath())
					->setParentId($parentId)
					->setName($CategoryName)
					->setIsActive(true);
				$category->save();
				return $category->getId();
			} else {
				return $cate->getId();
			}		
		} else {
			return "Please enter valid category name.";
		}		
	}				
}	
$my_script = new sk_scripts();
$my_script->save_product();

Thank you in advance.

Re: How to insert category programmatically in magento 2.3?

Hello Vimal

 

do you know as i can recovered the id abiti new category

 

thank Alessandro