Home / Magento / Create Magento 2 Customer Programmitically | How to add a customer programmatically in Magento 2 ?

Create Magento 2 Customer Programmitically | How to add a customer programmatically in Magento 2 ?

Create a php file on you magento 2 root path and past this code. Now Type Localhost/your_file_name.php or domain/your_file_name.php. First we include  app/bootstrap.php. now we can use magento 2 all functionality. Its inform to you, This is very unsecured and break the magento rules. use only if you must need this or Testing purpose.


<?php 
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');
 
$state = $objectManager->get('\Magento\Framework\App\State');
 
$state->setAreaCode('frontend');
 
// Customer Factory to Create Customer
 
$customerFactory = $objectManager->get('\Magento\Customer\Model\CustomerFactory');
 
$websiteId = $storeManager->getWebsite()->getWebsiteId();
 
$store = $storeManager->getStore(); // Get Store ID
 
$storeId = $store->getStoreId();
 
// Instantiate object (this is the most important part)
 
$customer = $customerFactory->create();
 
$customer->setWebsiteId($websiteId);
 
$customer->setEmail("hello2@example.com");
 
$customer->setFirstname("John");
 
$customer->setLastname("Doe");
 
$customer->setPassword('152452652');
 
$customer->save();
 
echo 'Create customer successfully'.$customer->getId();

Hits: 2

Leave a Reply