Create configurable product in Magento programmatically

Following post includes the code that can be used to create a configurable product in Magento.

Brief introduction about configurable product

When adding new products to your Magento store you have the option to select the type of the product. The most basic option is simple product.
That’s just a single item with no specific attributes/options that can be changed by the buyer.
With the configurable product type you can offer an item with some options that can be configured by the customers themselves.
For example, you can sell the same model of shoes that are offered in different colors, sizes, etc. Instead of creating several simple
products for each size of the same shoe model that will be displayed individually on the frontend,
for instance, you can create a configurable product which will allow the customer to select the size before ordering the product.

To understand the code, one must have a basic understanding of how configurable product works in a Magento store.

So, in general we will be creating number of simple products with specific attribute values that will bind to one configurable product(Visible on frontend). The code also contains the part in which we will create simple products first and pass some of its data to create configurable product. If you want a clear code to just add a simple product, please follow this: Create Simple Product in Magento Store Programmatically

 

Consider we have an array containing the information about the simple products. The array will somewhat look like this:

1
< ?php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
    umask(0);
    require 'app/Mage.php';
 
    $sp[0]['name'] = 'Some tshirt with size S';  
    $sp[0]['sku'] = 'tshirt_S';  
    $sp[0]['weight'] = 1;   
    $sp[0]['attribute_set_id'] = 4;   
    $sp[0]['description'] = 'descritpion about the product'; 
    $sp[0]['short_description'] = 'one line description about the product';    
    $sp[0]['type_id'] = Mage_Catalog_Model_Product_Type::TYPE_SIMPLE;      
    $sp[0]['status'] = Mage_Catalog_Model_Product_Status::STATUS_ENABLED;
    $sp[0]['visibility'] = Mage_Catalog_Model_Product_Visibility::VISIBILITY_NOT_VISIBLE;         
    $sp[0]['tax_class_id'] = 0;      
    $sp[0]['price'] = 1200; 
    $sp[0]['stock_data'] = array(   
                             'manage_stock' => 1,
                             'is_in_stock' => 1,
                             'qty' => 10,
                             'use_config_manage_stock' => 0
                 );
    $sp[1]['category_ids'] = array(2,3,5,7);
    $sp[1]['size'] = 'S';
    $sp[1]['name'] = 'Some tshirt with size M';
    $sp[1]['sku'] = 'tshirt_M';
    $sp[1]['weight'] = 1;
    $sp[1]['attribute_set_id'] = 4;
    $sp[1]['description'] = 'descritpion about the product';
    $sp[1]['short_description'] = 'one line description about the product';
    $sp[1]['type_id'] = Mage_Catalog_Model_Product_Type::TYPE_SIMPLE;
    $sp[1]['status'] = Mage_Catalog_Model_Product_Status::STATUS_ENABLED;
    $sp[1]['visibility'] = Mage_Catalog_Model_Product_Visibility::VISIBILITY_NOT_VISIBLE;
    $sp[1]['tax_class_id'] = 0;
    $sp[1]['price'] = 1200;
    $sp[1]['stock_data'] = array(
                            'manage_stock' => 1,
                            'is_in_stock' => 1,
                            'qty' => 11,
                            'use_config_manage_stock' => 0
                );
    $sp[1]['category_ids'] = array(2,3,5,7);
    $sp[1]['size'] = 'M';
 
?>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?php  
/**    returns the option id for any attribute code by passing the label                            $attribute_code e.g. 'size','color','article'  
$label e.g. 'M','Red','art_21312'   
*/      
function getOptionId($attribute_code,$label)   
{        
  $attribute_model = Mage::getModel('eav/entity_attribute'); 
  $attribute_options_model = Mage::getModel('eav/entity_attribute_source_table') ;                 $attribute_code = $attribute_model->getIdByCode('catalog_product', $attribute_code);
         $attribute = $attribute_model->load($attribute_code);
         $attribute_table = $attribute_options_model->setAttribute($attribute);
         $options = $attribute_options_model->getAllOptions(false);
 
         foreach($options as $option) 
         {
                if ($option['label'] == $label)
                {
                    $optionId=$option['value'];
                    break;
                }
         }
         return $optionId;
    }
?>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<?php         
 $simpleProducts = array();    
 foreach($sp as $product)    
 {
         $sProduct = Mage::getModel('catalog/product');
        $sProduct->setName($product['name']);
        $sProduct->setSku($product['sku']);
        $sProduct->setWeight($product['weight']);
        $sProduct->setAttributeSetId($product['attribute_set']);
        $sProduct->setDescription($product['description']);
        $sProduct->setShortDescription($product['short_description']);
        $sProduct->setTypeId($product['type_id'])
                 ->setWebsiteIds(array(1))
                 ->setStatus($product['status'])
                 ->setVisibility($product['visibility'])
                 ->setTaxClassId($product['tax_class_id']);
        $sProduct->setPrice($product['price']);
        $sProduct->setStockData($product['stock_data']);
        $sProduct->setCategoryIds($product['category_ids']);
        $optionId = getOptionId('size',$product['size']);
        $sProduct->setData('size',$optionId);
        $sProduct->save();
 
// we are creating an array with some information which will be used to bind the simple products with the configurable
        array_push(
                $simpleProducts,
                array(
                    "id" => $sProduct->getId(),
                    "price" => $sProduct->getPrice(),
                    "attr_code" => 'size',
                    "attr_id" => 129, // i have used the hardcoded attribute id of attribute size, you must change according to your store
                    "value" => $optionId,
                    "label" => $product['size'],
                )
            );
    }
?>

Time to create the configurable product

It also follows the same process as simple product, the tricky part comes in binding it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
< ?php    
 $cProduct = Mage::getModel('catalog/product');   
 $productData=array(
                       'name' => 'Main configurable Tshirt',
                       'sku' > 'tshirt_sku',
                       'description' => 'Clear description about your Tshirt that explains its features',
                       'short_description' => 'One liner',
                       'weight' => 1,
                       'status' => '1',
                       'visibility' => '4',
                       'attribute_set_id' => 4,
                       'type_id' => 'configurable',
                       'price' => 1200,
                       'tax_class_id' => 0,
                       'page_layout' => 'one_column',
                );
    foreach($productData as $key => $value)
    {
    	$cProduct->setData($key,$value);
    }
    $cProduct->setWebsiteIds(array(1));
    $cProduct->setStockData(array(
    		'manage_stock' => 1,
                'is_in_stock' => 1,
                'qty' => 0,
                'use_config_manage_stock' => 0
        ));
    $cProduct->setCategoryIds(array(2,3,5,7));
?>

Code to bind the products starts from here

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
< ?php         $cProduct->setCanSaveConfigurableAttributes(true);
    $cProduct->setCanSaveCustomOptions(true);
 
        $cProductTypeInstance = $cProduct->getTypeInstance();
        $attribute_ids = array(129);
        $cProductTypeInstance->setUsedProductAttributeIds($attribute_ids);
        $attributes_array = $cProductTypeInstance->getConfigurableAttributesAsArray();
        foreach($attributes_array as $key => $attribute_array) 
        {
            $attributes_array[$key]['use_default'] = 1;
            $attributes_array[$key]['position'] = 0;
 
            if (isset($attribute_array['frontend_label']))
            {
                $attributes_array[$key]['label'] = $attribute_array['frontend_label'];
            }
            else {
                $attributes_array[$key]['label'] = $attribute_array['attribute_code'];
            }
        }
        // Add it back to the configurable product..
        $cProduct->setConfigurableAttributesData($attributes_array);
 
        $dataArray = array();
        foreach ($simpleProducts as $simpleArray)
        {
            $dataArray[$simpleArray['id']] = array();
            foreach ($attributes_array as $key => $attrArray)
            {
                array_push(
                    $dataArray[$simpleArray['id']],
                    array(
                        "attribute_id" => $simpleArray['attr_id'][$key],
                        "label" => $simpleArray['label'][$key],
                        "is_percent" => 0,
                        "pricing_value" => $simpleArray['pricing_value'][$key]
                    )
                );
            }
        }
        $cProduct->setConfigurableProductsData($dataArray);
?>

Attach Images to Product

1
2
3
4
5
6
7
8
9
10
11
12
< ?php     // use the directory path to images you want to save for the product         $mode = array("image");     $img = 'full_directory_path_to_image_stored_img_0001.jpg';     $cProduct->addImageToMediaGallery($img, $mode, false, false);
 
    $mode = array("small_image","thumbnail","image");
    $img = 'full_directory_path_to_image_stored_img_0002.jpg';
    $cProduct->addImageToMediaGallery($img, $mode, false, false);
 
    $cProduct->save();
    echo "Wohoooo! Product saved 
"; 
 
    exit();
?>
Thats it to save a configurable product. I have used setData(‘attribute’,'attribute_value’) method in my previous post and setPrice(), setSku(), etc… methods to give an idea that both the methods can be used.

Ask your questions in comment section, if any

  • balram

    how can i add price variations if i have multiple options like
    color and size
    blue,xl
    blue,xxl
    like that
    have to add price variations for all variations

  • Parag

    There is one miner bug in import images code.
    So replace
    $mode = array(“small_image”,”thumbnail”,”image”);
    with
    $mode = array(“small_image”,”thumbnail”.”image”);

    • Jitendra Singh

      Sorry for typo Parag. It has been edited now.

  • vikas

    I don’t know php.

    I want to create the products programmatically in magento. everyone gave php code. no one mentioned in steps.

    1)where and in which folder I have to add the code.

    2)Is I have to save in .php file.

    3)Is there anything i have to add in app/code/core/Mage/catalog/php

    Thanks

    • Jitendra Singh

      @Vikas :
      1. You can put the code in root folder. As we are including (require ‘app/Mage.php’;) in our code, it will take care of all Magento’s core functions used during the process.
      2. Yes, you have to save it as php file
      3. No change/addition required in core files

      This is just a snippet to show what all function you can use to create a product. You can use them according to your ease in any location.

  • http://amatita.it antonio

    I have a similar snippet, i’m working around to configurable product about a week,i don’t see the product in frontend without save previous it in backend ,why?Any idea is appreciate
    regards

    • Jitendra Singh

      Antonio, There can be multiple reason for product not visible in front-end. Some of those which bothered me are :
      1. Not saving any attribute set for product.
      2. Status not enabled while saving the product in code.

      Its hard to say without looking at your code. Please try if you are missing anything from above or you can mail your snippet, i will look and try my best to solve it.

    • Jitendra Singh

      Also, try reindexing after creation of products through code. It will solve many problems.

  • vinit

    i m new in magento
    but where i have to add this code in magento core file
    pleas reply as soon as possible
    thanks

    • Jitendra Singh

      Vinit, no need to add this code in any core file, you can create a php file with this code in it in your magento root folder.
      Following lines will take care of executing core functions in your snippet :
      umask(0);
      require ‘app/Mage.php’;

  • http://abc brst

    i have to replace add attribute in configurable product and delete existing one for that product only…how???

  • May

    where did you get productData

    • Jitendra Singh

      I am creating this array with sample data for my product.
      $productData=array(
      ‘name’ =>; ‘Main configurable Tshirt’,
      ‘sku’ =>; ‘tshirt_sku’,
      ‘description’ =>; ‘Clear description about your Tshirt that explains its features’,
      ‘short_description’ =>; ‘One liner’,

      You can get this data from any source, say reading an excel file that contains product information.

  • luisdv

    Hi Jitendra,
    Thank you for the code snippet. I haven’t been able to get it to work though. I have put all the code in a single file and followed the instructions of putting the file in the root folder but all my attempts to create the configurable products have been unsuccessful. Am I missing something?

    • Jitendra Singh

      @luisdv : Can you provide some more details about your problem here?
      Is your file not executing at all. Or you are getting any error in between the execution. Try to provide complete error that you are getting, it will help in providing the solution faster.

      • luisdv

        @Jitendra.
        Thank you for your time. I really appreciate it. I’m new in Magento so I’m sure I’m doing something wrong. It appears that file is not executing at all. I put the code in a try block but I am not getting any error.
        I grabbed all the code as it is in your example to make a test, but after having a second look at the code I think I should first create the attributes size in Magento?
        Thanks again for all your help

        • Jitendra Singh

          @luisdv : Yes, you have to create an attribute based on which you want to create configurable product. I have used size as an attribute whose id is 129.
          You will have to use your attribute and corresponding id.
          Please refer to comment : // i have used the hardcoded attribute id of attribute size, you must change according to your store

    • joy

      hi,Please give me your email i will send you working code.

  • http://avashp.com.np Avash Poudel
  • joy

    Great article! Jitendar.
    I will appreciate if you can post similar article with multiple attribute like size and color for the configurable product.

    Thanks

  • parvinder

    Hello sir this script is not working at my end . is any version problem of magento… blank page showing … i placed file on root … please tell me what will be problem .. thanks

    • Jitendra Singh

      What version you are using?
      It works fine in 1.5.x and 1.6.x
      Please try to enable error reporting in your application. It will definitely give some error, if not working. Let me know the error, we can check issue then.

      • parvinder

        hello sir i am using version Magento ver. 1.8.1.0

        • Arpit

          parvinder,can you send us your code to ask@codetweet.com we will revert as soon as possible.

  • Arpit

    This above code is tried and tested.However, if you are still facing issues you can send your code to ask@codetweet.com with detailed issue.

  • Robin Michael

    Hi Jithnder, It is a fantastic code, While I insert simple product, Attribute Set Name is not appearing in Manage Products section and Inventory also not updating,, I am using the magento version 1.7.0.0

    • Jitendra Sisodiya

      Can you send your code to ask@codetweet.com along with screenshot of ‘Manage Product’ section where details are missing?
      Will look into the issue.

      Thanks

  • Ashutosh Bhardwaj

    I am also interested in knowing how to avail selection of attribute sets while adding products.
    Nice code anyway :-)

  • Diszo Sasil

    hahaha! hardcore developer… much better if you do this via import file :) no need to write code or ask server administrator for ftp/ssh accounts to upload and execute your code.

    • Jitendra Sisodiya

      @Diszo : Well, this can be useful for some people who don’t want to use Import feature as all of them might not have data in the format required.

      Also, one can right a simple API using this snippet as base to add products, which then can be called by 3rd party developer (This is just an example and came handy for a use case for me)

      Anyways, this totally depends on the requirement the person is having and can adopt any approach he/she feels comfortable. :)

      • Diszo Sasil

        Agreed. :)

  • abdessalem karray

    Hi,

    thinks for this code that was very helpful , i have meet one problem in the increase of price for one attribute ( $simpleArray['pricing_value'][$key] ) is never initialized , thinks to eclerate this part of code.

    thank you.

  • http://magentotutorial.net/ Quang Hiếu Phạm

    Yes, For Magento, you guys could go to magento beginner’s guide to learn magento from basic level.