Create Configurable Product Programmatically In Magento 2 For Beginners

by Trang Tran

Configurable products bring many benefits to an e-commerce store, both B2C and B2B. However, generating one by one may take a lot of time if you have an extensive catalog. In this case, creating configurable product programmatically can be a solution for Magento 2 store owners.

Programmatically creating items allows developers to quickly and easily set up online stores. When you need different colors and sizes for the same product, you’ll need to create a configurable product in Magento 2.

So let’s get started with the guide.

Who Should Create Configurable Product Programmatically in Magento 2?

Configurable products are a must-have for many firms since they allow visitors to examine the product’s choices. Magento comes with the ability to build and manage configurable products by default, with features such as flexible pricing, inventory management, delivery terms, and promotions.


However, when done manually, it takes time and effort to link multiple simple products to a configurable one. Thankfully, programmatically creating products helps developers set up online stores quicker.

This way can help save a lot of effort for those with an extensive catalog size. 

Consider creating configurable products programmatically in Magento 2 if you have coding knowledge. On the contrary, instead of taking risks without coding experience, you can seek help from reputable developers.

Check out our guide below:

How Do You Programmatically Create Configurable Products in Magento 2?

Step 1: Create a simple product programmatically

Instead of having to do each step in the backend dashboard as usual, in a programmatic way, you need to create a file in the Magento root directory and insert the following code:

$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); // instance of object manager
$product = $objectManager->create(‘\Magento\Catalog\Model\Product’);
$product->setSku(‘my-sku’); // Set your sku here
$product->setName(‘Sample Simple Product’); // Name of Product
$product->setAttributeSetId(4); // Attribute set id
$product->setStatus(1); // Status on product enabled/ disabled 1/0
$product->setWeight(10); // weight of product
$product->setVisibility(4); // visibility of product (catalog / search / catalog, search / Not visible individually)
$product->setTaxClassId(0); // Tax class id
$product->setTypeId(‘simple’); // type of product (simple/virtual/downloadable/configurable)
$product->setPrice(100); // price of product
                            ‘use_config_manage_stock’ => 0,
                            ‘manage_stock’ => 1,
                            ‘is_in_stock’ => 1,
                            ‘qty’ => 999999999

Step 2: Add an image to the product

After creating simple product, you need to add image to the product:

// Adding Image to product
$imagePath = “sample.jpg”; // path of the image
$product->addImageToMediaGallery($imagePath, array(‘image’, ‘small_image’, ‘thumbnail’), false, false);

Step 3: Add custom options (children product) to the product (parent product)

Next, create custom options and assign a simple one to them. Combining associated products with the current product is necessary to produce the configurable product.

// Adding Custom option to product
$options = array(
                    “sort_order”    => 1,
                    “title”         => “Custom Option 1”,
                    “price_type”    => “fixed”,
                    “price”         => “10”,
                    “type”          => “field”,
                    “is_require”   => 0
                    “sort_order”    => 2,
                    “title”         => “Custom Option 2”,
                    “price_type”    => “fixed”,
                    “price”         => “20”,
                    “type”          => “field”,
                    “is_require”   => 0
foreach ($options as $arrayOption) {
    $option = $objectManager->create(‘\Magento\Catalog\Model\Product\Option’)

Step 4: Assign associated products

To build a configurable product, follow the steps above and then execute the URL listed below

Follow this snippet to assign associated products to create configurable products programmatically in Magento 2. 

$productId = 12; // Configurable Product Id
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$product = $objectManager->create(‘Magento\Catalog\Model\Product’)->load($productId); // Load Configurable Product
$attributeModel = $objectManager->create(‘Magento\ConfigurableProduct\Model\Product\Type\Configurable\Attribute’);
$position = 0;
$attributes = array(134, 135); // Super Attribute Ids Used To Create Configurable Product
$associatedProductIds = array(2,4,5,6); //Product Ids Of Associated Products
foreach ($attributes as $attributeId) {
    $data = array(‘attribute_id’ => $attributeId, ‘product_id’ => $productId, ‘position’ => $position);
$product->setTypeId(“configurable”); // Setting Product Type As Configurable
$objectManager->create(‘Magento\ConfigurableProduct\Model\Product\Type\Configurable’)->setUsedProductAttributeIds($attributes, $product);
$product->setNewVariationsAttributeSetId(4); // Setting Attribute Set Id
$product->setAssociatedProductIds($associatedProductIds);// Setting Associated Products

Note that the command will fail if there is a duplicate assignment (the corresponding product is already allocated to a customizable product).

Tips for Simplify Configurable Products

The guide for Magento 2 create configurable product programmatically have extremely minimal capabilities and may be found in practically every retailer nowadays. So, what if you need some extra features? What if you’re a retailer who wants to boost client loyalty and give them a better shopping experience?

In such instances, Magento 2 extensions can be a savior. Magento 2 Improved Configurable Products by BSS Commerce is one of these additions.

The extension is a complete enhancement solution that, once loaded, improves the entire aesthetic and performance of configurable products while also providing a better shopping experience for clients.

>>> Wonder more specifically what Magento 2 Improved Configurable Products can do for you? CHECK OUT NOW!

The following are some tips to optimize the configurable product in Magento 2.

Product page enhancements

Magento’s default selection option display for configurable products makes it inconvenient for customers to order and review products.

Before adding a child product to the cart, customers must select each custom option and quantity. As a result, if they want many things, they cannot add numerous simple products to the shopping cart at once.

However, Magento 2 Simple Details on Configurable Product can give your product a unique identity and display details of all children items on one page. Hence, customers may quickly locate the appropriate child product based on color, size, and other characteristics.


As you can see, the extension covers practically every aspect of the product page and adds many useful features.

>>> Magento 2 create configurable products more easily with Magento 2 Simple Details on Configurable Product module.

Dynamic content update

You need this if you’re a supplier or manage a store where clients can buy many products and product variations simultaneously.

It is difficult to add all essential products to the cart when shopping for various product versions.

Thus, a dynamic content update will improve the shopping experience. Customers return to the stores where they feel most at ease. Besides, it also helps to increase the conversion rate due to precisely targeted advertisements.

With Magento 2 Configurable Product Matrix View, your customers know the variety they choose.


Second, because variations can differ, it’s critical to include a separate description for each Configurable Product variation.

Thirdly, the module, in addition to the core Magento 2 product pricing, supports advanced tiered prices and calculates the total price of a product immediately on the product page.

Pro tips for B2B store

Configurable products, even though they require more SKUs and may take longer to set up at first, give long-term benefits for both B2B business owners and customers.

The following are some of the most significant advantages of adopting configurable products for B2B stores:

  • Firstly, bulk B2B orders can be created and processed fast and efficiently. By leveraging  Magento 2 Configurable Product Wholesale Display, wholesale customers can add all chosen items to the cart at once. As a result, you can enhance the shopping experience, save time, etc.
  • Secondly, it allows for the easy implementation and display of tiered pricing
  • Thirdly, a configurable product’s supply of items can be tracked for different item combinations.
  • Lastly, the product pages appear well-designed. Magento 2 Customizable Product Wholesale Display will reduce the number of children products presented in the grid table by just displaying alternatives for one attribute on the table, allowing consumers to have a better perspective and place orders without being confused or making mistakes. As a result, the module will undoubtedly improve the appearance of configurable items.

>>>  Display all associated products in a grid table view with Magento 2 Customizable Product Wholesale Display module


Hopefully, you can easily practice with the above guide of Magento 2 create configurable product programmatically. Clear cache and reindex, as Magento requires, to see output on the frontend of your Magento 2 store.

As mentioned above, if you have no coding experience, you should carefully consider it. Otherwise, consider BSS Commerce third-party modules for more accessible display and management.

BSS Commerce is one of the leading Multi-platform eCommerce solutions and web development services providers worldwide. With experienced and certified developers, we commit to bringing high-quality products and services to optimize your business effectively.

CONTACT NOW to let us know your problems. We are willing to support you every time.

Next Reading Suggestions

© 2019 BSS Commerce owned by THANH CONG INTER ., JSC. All Rights Reserved.
Business registration certificate no. 0106064469 issued by Hanoi Department of Planning and Investment on 19 December 2019.
Legal Representative: Mr. Nguyen Quang Trung.