Create Simple Product in Magento Store Programmatically

 

We are creating a simple product programmatically in Magento Store. There is nothing much to describe in this post.
I am using the basic required information to create the product. May be your store needs more attributes to create the product, but to keep the post simple I am using just 2 custom created attributes.

 

14

 

Following script contains a function that gives the option id of option label for any attribute code.
For example, Magento needs the 321(assume option id for label “Black”) to save the value of attribute color.

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
< ?php   
umask(0);
require 'app/Mage.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;
    }
    // $sProduct is the object used for product creation
    $sProduct = Mage::getModel('catalog/product');
?>

Preparing the array that stores the product data

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
< ?php
    $productData=array(
                  'name' => "MY FIRST PRODUCT",
                  'sku' => "sku_123",
                  'description' => "A long description that suits yout product including its features",
                  'short_description' => "An one liner for your product",
                  'weight' => 1, // whatever your product weighs
                  'status' => 1, // 1 => enabled, 0 => disabled
                  'visibility' => '4', // 1 => Not Visible Individually, 2 => Catalog, 3 => Search, 4 => Catalog, Search
                  'attribute_set_id' => 4, // default
                  'type_id' => 'simple',
                  'price' => 1999,
                  'special_price' => 1599, // optional
                  'tax_class_id' => 0, // None
                  'page_layout' => 'one_column',
    );
    // traversing through each index of productData
    foreach($productData as $key => $value)
    {
        $sProduct->setData($key,$value); 
    }
 
    $sProduct('size',getOptionId('size','M'));
    $sProduct('size',getOptionId('color','Red'));
 
    $sProduct->setWebsiteIds(array(1));
?>

Assign quantity and stock status

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
< ?php
    $sProduct->setStockData(array(
                              'manage_stock' => 1,
                              'is_in_stock' => 1,
                              'qty' => 10,
                              'use_config_manage_stock' => 0
    ));
    $categoryIds = array(2,3,5); // Use category ids according to your store
    $sProduct->setCategoryIds($categoryIds);
    // 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';
    $sProduct->addImageToMediaGallery($img, $mode, false, false);
 
    $mode = array("small_image","thumbnail"."image");
    $img = 'full_directory_path_to_image_stored_img_0002.jpg';
    $sProduct->addImageToMediaGallery($img, $mode, false, false);
 
    // and finally you can call the save method to create the product
    $sProduct->save();
    echo "Pheww, Product saved Hurray :D";
 
    exit();
?>

Well this was easy, the tricky part comes in when we need to create the configurable product. Not to worry, it will be published in the next post.

  • http://localhost alok

    when insert by this images not visible on more views

    • Jitendra Singh

      Alok, you have to be more descriptive about your problem. Are images getting uploaded in product(admin) and not visible on frontend?
      Share more about your problem, i will be happy to help.

  • chris s

    hi. does this work in magento 1.9? thanks.

  • Arpit

    Hi Chris,

    Haven’t tested this code in magento 1.9,but i guess it will work.You can try and let us know.

  • Pepe

    Whre to put these file, and how Magento knows how to use it?

  • Arpit

    Hi Pepe,
    Put this file in your magento root folder.For example if your magento installation is like var\www\magento_1.8.Then this file would be placed in magento_1.8 directory.

    This statement -> require ‘app/Mage.php’; will know how to use this file.

  • http://uzodocs.com Bhushan

    Giving me error
    “PHP Fatal error: Function name must be a string in /home/storewal/public_html/mage_create_product.php on line 58″
    for this code.
    “$sProduct(‘size’,getOptionId(‘size’,'M’));”

    • Jitendra Singh

      @Bhushan : Did you created the function ‘getOptionId’ defined on line 8 ?

    • http://www.vuyani-software.com Melvin de Jong

      Hi, not sure if you still need it, but this may help others as well. I hade the same issue. I changed the code to:

      $sProduct -> setData (‘size’,getOptionId(‘size’,'M’));

      This fixed the issue for me on our custom import script.

  • miRRor

    Also It gave me this error when running the script:
    Fatal error: Call to a member function getModelInstance() on a non-object in /var/www/magento_1_9/app/Mage.php on line 463

    – fixed it with
    Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);

    after function definition

  • Muhammad Azeem

    Awesome. Working great for Magento ver. 1.8.1.0. Exactly what i was looking for.
    Thanks

  • Mon

    Hi Jitendra! Thanks for this solution. It’s working perfect but i have a issue. I can’t save value for custom attributes when create products. You have any idea for this issue? Thank again :)

  • Rajesh Wellington

    I am new new to magento… My question is little funny… Where to add all these codes..!! LOL :P

    • http://www.codetweet.com/ Jitendra Sisodiya

      Hi Rajesh,

      You can put this code snippet in Magento’s root directory.

  • Pablo

    i get this error Fatal error: Call to a member function getModelInstance() on a non-object in /home/eyepster/public_html/app/Mage.php on line 463

    • Pablo

      fix it! just add Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID); before // $sProduct is the object used for product creation
      $sProduct = Mage::getModel(‘catalog/product’);

  • Dhananjay Singh

    Hi i am getting error

    Fatal error: Uncaught exception ‘Mage_Core_Exception’ with message ‘The product could not be found.’ in /public_html/clients/preptable/app/Mage.php:595 Stack trace: #0 /public_html/clients/preptable/app/code/core/Mage/Checkout/Model/Cart.php(211): Mage::throwException(‘The product cou…’) #1 /public_html/clients/preptable/app/code/core/Mage/Checkout/Model/Cart.php(248): Mage_Checkout_Model_Cart->_getProduct(Object(Mage_Catalog_Model_Product)) #2 /public_html/clients/preptable/product1.php(40): Mage_Checkout_Model_Cart->addProduct(Object(Mage_Catalog_Model_Product), Object(Varien_Object)) #3 {main} thrown in /public_html/clients/preptable/app/Mage.php on line 595

    I have added a product by code in magento 1.9 then i am trying to add same product into cart, it shows this error, but if i go into admin and then save that product again then add same product into cart by code, it works, so the problem is when i add product in magento by code and then in next line i add it in cart using below code it shows this error.

    $session = Mage::getSingleton(‘customer/session’);

    $cart = Mage::getSingleton(‘checkout/cart’);

    $cart->init();

    //Mage::getSingleton(‘checkout/cart’)->truncate();

    $productInstance = Mage::getModel(‘catalog/product’)->load($productId);

    $params = array(

    ‘product’ => $productInstance->getId(),

    ‘qty’ => 1,

    ‘options’ => $optionvalue

    );

    $request = new Varien_Object();

    $request->setData($params);

    $cart->addProduct($productInstance, $request);

    $session->setCartWasUpdated(true);

    $cart->save();

    Any help would be really apprecitaed i have tried a lot of codes but none of them seems to be working.

  • Wasim Akram

    Hi

    i want to know that how header menu is working with the admin dashboard like when someone adding the product the automatically show at frontend so can anyone tell me that how its works and what is the file name to see what the coding part……..

    any help would be much appreciated……… thanks.

  • Patrickbenn

    Nice one and i need to add multiple simple product from csv file can you please advice me how to do that….

    Thanks,