How to Create Configurable Product Programmatically in Magento 2

Hello Magento Folks,

Welcome to Create Product Programmatically in Magento 2 series where I will illustrate how to create configurable products programmatically in Magento 2. 

If you are reading this tutorial then you are probably new to Magento. Therefore, firstly check out the types of products in my previous blog Magento 2 Product Types: All You Need to Know Guide. Basically, creating products programmatically helps the developers to set up online stores effortlessly. When there is a requirement for different colors and sizes for the same product then in Magento you will need to create a configurable product. 

Mainly we can create 6 types of products Programmatically in Magento 2:

Steps to create configurable product programmatically in Magento 2:

Step 1: Firstly create a configurable_product.php file in the Magento root directory and add the below-given code

<?php
use Magento\Framework\AppInterface;
try {
    require_once __DIR__ . '/app/bootstrap.php';
} catch (\Exception $e) {
    echo 'Autoload error: ' . $e->getMessage();
    exit(1);
}
try {
    $bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER);
    $objectManager = $bootstrap->getObjectManager();
    $appState = $objectManager->get('Magento\Framework\App\State');
    $appState->setAreaCode('frontend');

    $configurableproduct = $objectManager->create('Magento\Catalog\Model\Product');
    $configurableproduct->setSku("configurable_sku"); // set Your SKU
    $configurableproduct->setName("Configurable Name"); // set Your Configurable Name
    $configurableproduct->setAttributeSetId(4); // set attribute id
    $configurableproduct->setStatus(1); // status enabled/disabled 1/0
    $configurableproduct->setTypeId('configurable'); // type of product (simple/virtual/downloadable/configurable)
    $configurableproduct->setVisibility(4);  // visibility of product (Not Visible Individually (1) / Catalog (2)/ Search (3)/ Catalog, Search(4))
    $configurableproduct->setPrice(0);
    $configurableproduct->setTaxClassId(0); // Tax class ID
    $configurableproduct->setWebsiteIds(array(1)); // set website Id
    $category_id = array(2, 3);
    $configurableproduct->setCategoryIds($category_id);
    $configurableproduct->setStockData(array(
            'use_config_manage_stock' => 0,
            'manage_stock' => 1,
            'is_in_stock' => 1,
        )
    );
    $configurableattributesdata = $configurableproduct->getTypeInstance()->getConfigurableAttributesAsArray($configurableproduct);
    $configurableproduct->setCanSaveConfigurableAttributes(true);
    $configurableproduct->setConfigurableAttributesData($configurableattributesdata);
    $configurableproductsdata = array();
    $configurableproduct->setConfigurableProductsData($configurableproductsdata);
    try {
        $configurableproduct->save();
    } catch (Exception $ex) {
        echo '<pre>';
        print_r($ex->getMessage());
        exit(1);
    }
    $product_id = $configurableproduct->getId();
    $associatedproductids = array(1,9);
    try {
        $configurableproduct_load = $objectManager->create('Magento\Catalog\Model\Product')->load($product_id);
        $configurableproduct_load->setAssociatedProductIds($associatedproductids);
        $configurableproduct_load->setCanSaveConfigurableAttributes(true);
        $configurableproduct_load->save();
        echo "configurable product save successfully";
    } catch (Exception $e) {
        echo "<pre>";
        print_r($e->getMessage());
        exit(1);
    }
}catch (Exception $e) {
    echo "<pre>";
    print_r($e->getMessage());
    exit(1);
}

Step 2: After the above step you will need to run the below-given URL to create a configurable product.

https://yourdomain.com/configurable_product.php

Wrapping Up:

Hopefully, all are able to create configurable products programmatically in Magento 2 using the above code. As customary of Magento, clear cache and reindex to display output on the frontend of your Magento 2 store. Let me know implementation concerns in the comment section below. You can also take our certified developer’s help using the Magento Multi-Store & Website Setup Service. 

Share with your friends via social media.

Happy Reading!

Previous Article

How to Create Simple Product Programmatically in Magento 2

Next Article

How to Create Grouped Product Programmatically in Magento 2

Write a Comment
  1. Baljinder Singh

    Hey Dhiren

    I am having an excel sheet of products exported from WordPress store.
    I have created same product attributes in magento. Now I want to import products to magento with code.
    Above code is fine but I am clear how to add attribute data to array.
    Could you please help me out .
    Thanks

    1. You need to do the customization of the above code, Instead of static data value for the product,
      Read data from your CSV file one by one and create a product.

  2. andy Copping

    we have 600,00 simple products and this would be great to made in to configurable products but how will it know which simple products to add in to the configurable one. Also will this code also add all the images from the simple product in to the configurable product main gallery?

    1. This line bind the simple products with configurable products : $associatedproductids = array(1,9);
      And this code do not add simple product images to configurable products.

Leave a Comment

Your email address will not be published. Required fields are marked *

Get Connect With Us

Subscribe to our email newsletter to get the latest posts delivered right to your email.
Pure inspiration, zero spam ✨