How To Create Magento 2 Store Programmatically

I would like to know if there is any way can create a Magento 2’s store programmatically.

You can call ‘StoreFactory’ class to create Magento 2’s website and use the store resource model to save the store object. Here is the example to create a Magento 2’s store programmatically

$storeFactory = \Magento\Framework\App\ObjectManager::getInstance()
            ->get('Magento\Store\Model\StoreFactory');
$storeResourceModel = \Magento\Framework\App\ObjectManager::getInstance()
            ->get('use Magento\Store\Model\ResourceModel\Store');
$websiteFactory = \Magento\Framework\App\ObjectManager::getInstance()
            ->get('Magento\Store\Model\WebsiteFactory');

$eventManager = \Magento\Framework\App\ObjectManager::getInstance()
            ->get('Magento\Framework\Event\ManagerInterface');


$website = $websiteFactory->create();
$website->load('your_website');
$groupid = 1;

$store= $storeFactory->create();
$store->setCode('new_store');
$store->setName('New Store');
$store->setWebsite($website);
$store->setGroupId($groupid);
$store->setData('is_active','1');
$storeResourceModel->save($store);

$eventManager->dispatch('store_add', ['store' => $store]);
0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments