Having your customers divided into groups can benefit your sales greatly. This helps to find a personalized approach and target the right customers with the right messages. To say nothing of the enhanced store performance and shopping experience.
You can certainly create Magento 2 customer group in the admin panel. Yet, if you'd like to manage this task through coding, there is an option for you too. And in this article, you'll learn how to create a customer group in Magento 2 programmatically.
Create Customer Group Using Dependency Injection
Using dependency injection, create a file in your module, and then call the execute function of that class CreateCustomerGroup in any place of your code to create a customer group.
<?php namespace Vendor\Extension\Model;
use Magento\Customer\Model\GroupFactory;
class CreateCustomerGroup
{
protected $groupFactory;
public function __construct(GroupFactory $groupFactory)
{
$this->groupFactory = $groupFactory;
}
public function execute(string $customerCode, int $taxClassId) {
$group = $this->groupFactory->create();
/* Creating a Customer Group */
$group->setCode($customerCode)
->setTaxClassId($taxClassId)
->save();
}
}
Create Customer Group Using Object Manager
Though it might seem easier, before using it note that object manager hides real dependencies of the class.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
use Magento\Framework\App\Bootstrap;
require __DIR__ . '/app/bootstrap.php';
$bootstrap = Bootstrap::create(BP, $_SERVER);
$obj = $bootstrap->getObjectManager();
$state = $obj->get(Magento\Framework\App\State::class);
$state->setAreaCode('adminhtml');
$customerGroupFactory = $obj->create(\Magento\Customer\Model\GroupFactory::class);
$group = $customerGroupFactory->create();
/* Creating a Customer Group */
$group->setCode('New Customer Group 1')
->setTaxClassId(3)
->save();
And that would be it. It wasn't hard at all, was it?
Yet, after customer groups are created, you should assigning customers to them. This is a perfect way to structure your store data and ensure an efficient customer experience.