Magento Tutorials

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!

Click to rate this post!
[Total: 5 Average: 5]
Dhiren Vasoya

Dhiren Vasoya is a Director and Co-founder at MageComp, Passionate 🎖️ Certified Magento Developer👨‍💻. He has more than 9 years of experience in Magento Development and completed 850+ projects to solve the most important E-commerce challenges. He is fond❤️ of coding and if he is not busy developing then you can find him at the cricket ground, hitting boundaries.🏏

View Comments

  • 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

    • 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.

Recent Posts

How to Integrate ChatGPT with Laravel Application?

In this guide, we'll explore how to integrate ChatGPT, an AI-powered chatbot, with a Laravel…

1 day ago

What are Net Sales? How to Calculate Your Net Sales?

In the world of business, understanding financial metrics is crucial for making informed decisions and…

3 days ago

Magento 2 Extensions Digest April 2024 (New Release & Updates)

Welcome to the MageComp Monthly Digest, where we bring you the latest updates, releases, and…

3 days ago

The ABCs of Geofencing: Definition, Features and Uses

In this era, businesses are always on the lookout for ways to engage with their…

4 days ago

How to Delete Product Variant in a Shopify Remix App using GraphQL Mutations?

Managing a Shopify store efficiently involves keeping your product catalog organized. This includes removing outdated…

5 days ago

6 Innovative Tools Revolutionizing E-Commerce Operations

E-commerce has transformed the way consumers shop for products and services and interact with businesses.…

1 week ago