Milind Daraniya

How to Create Customer Group Programmatically in Magento 2 using a Single Script

Published September 14th, 2023 12 min read

In Magento 2, you can create customer groups programmatically using a single script. This can be helpful when setting up your store programmatically or automating certain tasks. In this tutorial, we'll guide you through the process of creating a customer group programmatically in Magento 2 using a single script.

Step 1: Create the PHP Script

First, create a new PHP script file (e.g., create_customer_group.php) in your Magento 2 root directory or in a custom module directory.

Step 2: Include Magento's Bootstrap File

Include Magento's bootstrap file to access Magento's functionalities within the script:

<?php
use Magento\Framework\App\Bootstrap;
require __DIR__ . '/app/bootstrap.php';

$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();

Step 3: Create the Customer Group

Now, you can create the customer group programmatically. The customer group name and code should be unique.

<?php
use Magento\Framework\App\Bootstrap;
require __DIR__ . '/app/bootstrap.php';

$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();

// Customer Group Data
$groupName = 'VIP Customers'; // Replace with your desired group name
$groupCode = 'vip_customers'; // Replace with your desired group code

// Check if the group already exists
$groupFactory = $objectManager->get(\Magento\Customer\Model\GroupFactory::class);
$group = $groupFactory->create()->load($groupCode, 'customer_group_code');
if ($group->getId()) {
    echo "Customer group with code '$groupCode' already exists.\n";
} else {
    // Create the new customer group
    $groupData = [
        'customer_group_code' => $groupCode,
        'tax_class_id' => 3, // Replace with the desired tax class ID (optional)
        'group_code' => $groupCode,
        'tax_class_name' => 'Retail Customer' // Replace with the desired tax class name (optional)
    ];

    $group = $groupFactory->create();
    $group->setData($groupData);
    $group->save();
    echo "Customer group '$groupName' created successfully with code '$groupCode'.\n";
}

Step 4: Run the Script

Save the PHP script and run it from the command line in your Magento 2 root directory:

php create_customer_group.php

Conclusion

With this single PHP script, you can programmatically create a customer group in Magento 2. This approach can be useful for automating the setup of customer groups in your Magento store or for any other custom development needs. Remember to replace the placeholders with the desired customer group name and code. Happy coding!