In Magento 2, a new customer account is created via sign up. Also, customer registration is possible via admin panel. But, as a store owner, what if you want to add a huge number of new customers manually? The task becomes tedious as you have to create the customer accounts having different addresses and need to assign them in different groups. It is not feasible to manually create each customer in such case. The smarter way is to get customer data from attribute value in Magento 2 and create customers programmatically in Magento 2.
The method discussed here allows to programmatically create customers and assign to a customer group. Save time and get your task done quickly!
Method to create customers programmatically in Magento 2:
<?php use Magento\Framework\App\Bootstrap; require 'app/bootstrap.php'; $bootstrap = Bootstrap::create(BP, $_SERVER); $objectManager = $bootstrap->getObjectManager(); $state = $objectManager->get('\Magento\Framework\App\State'); $state->setAreaCode('frontend'); $storeManager = $objectManager->get('\Magento\Store\Model\StoreManagerInterface'); $storeId = $storeManager->getStore()->getId(); $websiteId = $storeManager->getStore($storeId)->getWebsiteId(); try { $customer = $objectManager->get('\Magento\Customer\Api\Data\CustomerInterfaceFactory')->create(); $customer->setWebsiteId($websiteId); $email = '[email protected]'; $customer->setEmail($email); $customer->setFirstname("test first"); $customer->setLastname("test last"); $hashedPassword = $objectManager->get('\Magento\Framework\Encryption\EncryptorInterface')->getHash('MyNewPass', true); $objectManager->get('\Magento\Customer\Api\CustomerRepositoryInterface')->save($customer, $hashedPassword); $customer = $objectManager->get('\Magento\Customer\Model\CustomerFactory')->create(); $customer->setWebsiteId($websiteId)->loadByEmail($email); } catch (Exception $e) { echo $e->getMessage(); }
Run the above code in a loop and create multiple customers at a time, changing the email ID every time.
You may also love to rea: Create customer using rest API in Magento 2
Thank you