Hello Magento Friends,
Today I am going to provide a solution on How to Create Customer Groups Programmatically in Magento 2.
Let’s see the requirement for customer groups and steps to create customer groups in Magento 2.
Why is it necessary to Create Customer Groups in Magento 2?
Customers are the most important factor of consideration for E-commerce shop owners. A customer might not be interested in everything you sell or all the products of your Magento store may not be suitable for all types of customers. This is where the Magento store owners need to classify customers based on age, location, interests, and more. This can be done by creating Customer Groups. Customer groups can help to provide a personalized shopping experience to customers and show the right product to the right audience.
Default Magento provides the feature to group customers from the backend configuration. Instead integrate Auto Customer Group Switching for Magento 2 to automatically move customers to a specific group based on conditions.
Say, now you have a requirement to create a custom customer group for your Magento 2 store. Move forward with this article, to accomplish How to Create Customer Groups Programmatically in Magento 2.
Steps to Create Customer Groups Programmatically in Magento 2:
Step 1: Create InstallData.php at the given below path
app\code\Vendor\Extension\Setup\InstallData.php
Now, add the below code
<?php namespace Vendor\Extension\Setup; use Magento\Framework\Setup\InstallDataInterface; use Magento\Framework\Setup\ModuleContextInterface; use Magento\Framework\Setup\ModuleDataSetupInterface; use Magento\Customer\Model\GroupFactory; class InstallData implements InstallDataInterface { protected $groupFactory; public function __construct(GroupFactory $groupFactory) { $this->groupFactory = $groupFactory; } public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context) { $setup->startSetup(); $group = $this->groupFactory->create(); /* For Creating a Single Customer Group */ $group->setCode('New Customer Group') ->setTaxClassId(3) ->save(); /* For Creating a Multiple customer group */ $setup->getConnection()->insertForce( $setup->getTable('customer_group'), ['customer_group_code' => 'NewCustomerGroup1', 'tax_class_id' => 3] ); $setup->getConnection()->insertForce( $setup->getTable('customer_group'), ['customer_group_code' => 'NewCustomerGroup2', 'tax_class_id' => 3] ); $setup->endSetup(); } }
Conclusion:
This way you can Create Customer Groups Programmatically in Magento 2. Once you have created a customer group, you can easily Manage Customer and Customer Groups in Magento 2 using the admin panel.
If you face any hardship with the above steps, feel free to get in touch with me via the comment section. Share the article with your developer friends. Continue to check our latest updates.
Happy Coding!