create category programmatically – magento 2

create category programmatically – magento 2

Magento 2 create category programmatically is a timely topic so that you can work on custom magento 2 extension, for example, in the right way. Welcome here, onlinecode Tutorial! The exact steps are listed with the specific script in PHP to create the category attributes.

By the availability of the setup scripts, there is no need to waste time learning or modifying anything while you don’t have experience in coding. The only thing you need to do is copying and pasting the following snippets to your module. Here are the snippets that you can achieve immediately.

// code for create category programmatically - magento 2
use \Magento\Framework\App\Bootstrap;
// include magento bootstrap file
include('../app/bootstrap.php');

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

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

// we Get Root Category ID
$root_node_id = $mage_store->getRootCategoryId();
echo 'rootNodeId: '.$root_node_id." ";
// we Get Root Category
$root_cat_id = $object_Manager->get('Magento\Catalog\Model\Category');
$cat_info = $root_cat_id->load($root_node_id);

$categorys_data = array('Levis','Wranglers','Basics'); // we Category Names
foreach($categorys_data as $cat_val)
{
	// catagory name
	$cat_name = ucfirst($cat_val);
	$site_url = strtolower($cat_val);
	$clean_url = trim(preg_replace('/ +/', '', preg_replace('/[^A-Za-z0-9 ]/', '', urldecode(html_entity_decode(strip_tags($site_url))))));
	$category_factory=$objectManager->get('\Magento\Catalog\Model\CategoryFactory');
	// Add a new sub category under root category
	$category_obj = $category_factory->create();
	$category_obj->setName($cat_name);
	$category_obj->setIsActive(true);
	$category_obj->setUrlKey($clean_url);
	$category_obj->setData('description', 'description');
	$category_obj->setParentId($root_cat_id->getId());
	$mediaAttribute = array ('image', 'small_image', 'thumbnail');
	$category_obj->setImage('/catagory_img.png', $mediaAttribute, true, false);
	// add image at Path of  pub/meida/catalog/category/catagory_img.png
	// add store id 
	$category_obj->setStoreId($store_Id);
	$category_obj->setPath($root_cat_id->getPath());
	// save category
	$category_obj->save();
}

create category programaticaly if not exist – magento 2

magento 2 create category programaticaly but it will not create category if category is exist. it will only unique create category programmatically create.

// code for create category programmatically - magento 2
$parent_cat_id = \Magento\Catalog\Model\Category::TREE_ROOT_ID;

$parent_category = $this->_objectManager
                      ->create('Magento\Catalog\Model\Category')
                      ->load($parent_cat_id);
$category_obj = $this->_objectManager
                ->create('Magento\Catalog\Model\Category');
// Check category exist or not
$cate_data = $category_obj->getCollection()
            ->addAttributeToFilter('name','CATE_NAME')
            ->getFirstItem();

if(!isset($cate_data->getId())) 
{
    $category_obj->setPath($parent_category->getPath())
        ->setParentId($parent_cat_id)
        ->setName('CATE_NAME')
        ->setIsActive(true);
    $category_obj->save();
}

You also like Get Order Details using Order and customer registration programmatically and Magento2 admin login user detail and Magento 2 Featured products

Leave a Comment

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

9  +  1  =  

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