Programmatically (manually) creating simple Magento product

Programmatically (manually) creating simple Magento product

In a development process, you often need some testing data you can use. Magento supplies you with it’s default Sample Data that contains some products. Thing is, they’re not of much use if you have some custom attributes added to your products, if you create your own attribute set, or a product type.

For this, you’ll need to add some products yourself.

Sometimes, doing so in the administration is enough, but it gets painful when you need to add multiple products, or if you’re still developing some feature, and making changes on the fly.

This problem can be easily solved by adding products programmatically.

I’ll show you an example on how to add a simple product this way. You could modify this code a bit, and make it work for other product types, or even use it as an import script.

You can call this through an observer, set is as a controller action, or cheat and call it from a view file, whichever you think is best. Just pay attention, that if you observe some event, don’t use the ones that get called on every controller action. Or, if you do, be sure to check if the product with the same SKU already exists, by loading product’s ID by SKU before the attempt to create it. For this, you can use the ‘if’ check on lines 4 and 49 in the code example below.

If you don’t do that, you’ll get SQL errors line the following one:

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '193-1' for key 'UNQ_CATALOGINVENTORY_STOCK_ITEM_PRODUCT_ID_STOCK_ID'

Let’s get to the code I’m talking about.

<?php
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
$product = Mage::getModel('catalog/product');
// if(!$product->getIdBySku('testsku61')):
 
try{
$product
// ->setStoreId(1) //you can set data in store scope
->setWebsiteIds(array(1)) //website ID the product is assigned to, as an array
->setAttributeSetId(9) //ID of a attribute set named 'default'
->setTypeId('simple') //product type
->setCreatedAt(strtotime('now')) //product creation time
// ->setUpdatedAt(strtotime('now')) //product update time
 
->setSku('testsku61') //SKU
->setName('test product21') //product name
->setWeight(4.0000)
->setStatus(1) //product status (1 - enabled, 2 - disabled)
->setTaxClassId(4) //tax class (0 - none, 1 - default, 2 - taxable, 4 - shipping)
->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH) //catalog and search visibility
->setManufacturer(28) //manufacturer id
->setColor(24)
->setNewsFromDate('06/26/2014') //product set as new from
->setNewsToDate('06/30/2014') //product set as new to
->setCountryOfManufacture('AF') //country of manufacture (2-letter country code)
 
->setPrice(11.22) //price in form 11.22
->setCost(22.33) //price in form 11.22
->setSpecialPrice(00.44) //special price in form 11.22
->setSpecialFromDate('06/1/2014') //special price from (MM-DD-YYYY)
->setSpecialToDate('06/30/2014') //special price to (MM-DD-YYYY)
->setMsrpEnabled(1) //enable MAP
->setMsrpDisplayActualPriceType(1) //display actual price (1 - on gesture, 2 - in cart, 3 - before order confirmation, 4 - use config)
->setMsrp(99.99) //Manufacturer's Suggested Retail Price
 
->setMetaTitle('test meta title 2')
->setMetaKeyword('test meta keyword 2')
->setMetaDescription('test meta description 2')
 
->setDescription('This is a long description')
->setShortDescription('This is a short description')
 
->setMediaGallery (array('images'=>array (), 'values'=>array ())) //media gallery initialization
->addImageToMediaGallery('media/catalog/product/1/0/10243-1.png', array('image','thumbnail','small_image'), false, false) //assigning image, thumb and small image to media gallery
 
->setStockData(array(
'use_config_manage_stock' => 0, //'Use config settings' checkbox
'manage_stock'=>1, //manage stock
'min_sale_qty'=>1, //Minimum Qty Allowed in Shopping Cart
'max_sale_qty'=>2, //Maximum Qty Allowed in Shopping Cart
'is_in_stock' => 1, //Stock Availability
'qty' => 999 //qty
)
)
 
->setCategoryIds(array(3, 10)); //assign product to categories
$product->save();
//endif;
}catch(Exception $e){
Mage::log($e->getMessage());
}

We’re setting this product in ‘Default Values‘ scope. You can uncomment the code on line 5 to set product data for a specific store. For example, you could do this:

...
->setMetaTitle('test meta title 2')
->setMetaKeyword('test meta keyword 2')
->setMetaDescription('test meta description 2')
->setStoreId(2)
->setMetaTitle('Some other meta title')
->setMetaKeyword('Some other meta keyword')
->setMetaDescription('Some other meta description')
$product->save();

The code above will set different meta values in store with an ID of 2.

You can find all the values you are able to set for the product by logging the post data on product save. I’m thinking of saveAction in the ProductController that gets called from Magento administration when you’re saving a product.

app/code/core/Mage/Adminhtml/controllers/Catalog/ProductController.php

public function saveAction()
{
$storeId = $this->getRequest()->getParam('store');
$redirectBack = $this->getRequest()->getParam('back', false);
$productId = $this->getRequest()->getParam('id');
$isEdit = (int)($this->getRequest()->getParam('id') != null);
 
$data = $this->getRequest()->getPost();
if ($data) {
Mage::log($data);

Just add the last line to the file. Be sure to delete it when you’re done developing, though. This will get you an array of data you can save. For example for setting [meta_title], you’ll use a magic method setMetaTitle(‘somevalue’).

Note: This is a revamp of an article originally written in July 2009.

If you’re still having some doubts or feel like you need help regarding your store, we’re here to help. Feel free to drop us a line to get your site checked out by our team of experts who can offer valuable insights and identify potential solutions on your road to building better Magento sites!

Related Inchoo Services

You made it all the way down here so you must have enjoyed this post! You may also like:

Shell script for converting configurable to grouped products Tsvetan Stoychev
Tsvetan Stoychev, | 5

Shell script for converting configurable to grouped products

Programmatically create bundle products in Magento Petar Sambolek
Petar Sambolek, | 5

Programmatically create bundle products in Magento

Programmatically create a configurable Magento product Petar Sambolek
Petar Sambolek, | 20

Programmatically create a configurable Magento product

40 comments

  1. HI, I am using 1.9.2 version. I successfully could insert products trough csv upload except stock quantity (manage stock is aslo selected as “no”) & images. Can u please help me. Or somebody who have done this successfully.

  2. product is not visible on frontend
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();

    $product = $objectManager->create(‘\Magento\Catalog\Model\Product’);

    $mage_pid = $product->getId();

    $product->setSku($post[‘customproduct_sku’]); // Set your sku here
    $product->setName($post[‘customproduct_name’]); // Name of Product
    $product->setAttributeSetId(9); // Attribute set id
    $product->setStatus(1); // Status on product enabled/ disabled 1/0
    $product->setWeight(10); // weight of product
    $product->setVisibility(4); // visibilty of product (catalog / search / catalog, search / Not visible individually)
    $product->setTaxClassId(2); // Tax class id
    $product->setTypeId(‘simple’); // type of product (simple/virtual/downloadable/configurable)
    $product->setPrice($post[‘customprice’]); // price of product
    $product->setCategoryIds($data[‘customproduct_category’]);

  3. Nice Answer , but i have 1 query when i add the custom product , but it is not showing on front end ,please help me

  4. Hi what changes do I have to make if I add product for a particular attribute set. Except for attributesetID what else would change?

    1. Hi Vishnu,

      have you been able to add products programmatically in Magento 2 ? Could you please share your code ?

  5. I have inserted your code and it’s working perfectly on my Local Computer, though when I uploaded it on the Hosting Server it’s giving Invalid Date
    I have updated the created date a lot of time, but the error is still the same, could anyone assist me with this

    thanks a million

  6. I forgot the error:

    INSERT INTO `catalog_product_entity` (`entity_type_id`, `attribute_set_id`, `type_id`, `sku`, `created_at`, `updated_at`) VALUES (?, ?, ?, ?, ‘2015-10-08 07:40:56’, ‘2015-10-08 07:40:56’)

  7. hi it is very useful but when we try to added product description in custom created product then not change show on frontend please suggest

  8. Hi everyone,

    is it possible to set the image path to any relative path like

    media/catalog/product/<brand>/<filename>.png"

    using addImageToMediaGallery or does the path have to follow magento’s directory structure as shown in the given example?

    Thanks,
    David

    1. I put in this code inside of the magento file name is sample.php

      Fatal error: Class ‘Mage’ not found in C:\xampp\htdocs\magento\sample.php on line 2

  9. Very nice tutorial.

    I want to set the custom option titles on the based of the storeview. For example my website have three views.
    default
    English
    Arabic

  10. Very nice tutorial.

    I want to set the custom option titles on the based of the storeview. For example my website have four views
    default
    English
    Chinese
    Japanese

    My custom option title is color and it’s option are red, and black for English. How can i set these titles for Chinese storeview.? Thank you very much.

  11. I want to add Fixed Product Tax and i adding it as following

    $fpt	= array('website_id'=>0,
    				'country'=>'IN',
    				'state'=>'*',
    				'value'=>10.00,
    				'website_value'=>10);
    		$loadpro->setFPT(array($salesTax));

    FPT is the attribute name.
    When i am adding from admin then it is saving the FPT value but when i added using the code then it deleted the existing FPT value.

    Could you please help with this?

    Thank You

  12. I tried same in 1.9.1 but product didn’t displayed at backend or not even in frontend. i run indexing, clear cache but didnt work also i check in db it exist catalog_product_entity table having a new entry but not displayed at frontend. i am having multiple websites and multiple stores

    1. I also tried it in magento 1.9.1 , its working fine without any problem . You need to check object , that u are using correctly or not. Don’t copy paste , just use $product in a right way.

  13. Hi,
    Very nice tutorial, thanks for this post, I want to know that
    >> How can i add more than 1 image at a time how could i do that?
    >> How can i add a image from an external URL.

    Like example, my image path is
    http:// -inchoo.net- /magento/files/product1.jpg
    http:// -inchoo.net- /magento/files/product2.jpg
    http:// -inchoo.net- /magento/files/product3.jpg
    http:// -inchoo.net- /magento/files/product4.jpg
    http:// -inchoo.net- /magento/files/product5.jpg

    Please Help me on this 2 point
    thank you again for this post.

  14. If i have set the ->setStoreId(1), how can i unset it? My products don’t show up in “Manage Products” but i can acces them directly with ID.

    But I comment out the // ->setStoreId(1) then everything is ok.

    So the question is how I can undo setStoreId for those products, which i did set the store ID.

  15. how can i update simple product i am facing this error “Fatal error: Uncaught exception ‘Exception’ with message ‘Warning: Invalid argument supplied for foreach() in /home3/neuwdeni/public_html/dev/app/code/core/Mage/Eav/Model/Entity/Abstract.php on line 1180’ in /home3/neuwdeni/public_html/dev/app/code/core/Mage/Core/functions.php:245 Stack trace: #0 /home3/neuwdeni/public_html/dev/app/code/core/Mage/Eav/Model/Entity/Abstract.php(1180): mageCoreErrorHandler(2, ‘Invalid argumen…’, ‘/home3/neuwdeni…’, 1180, Array) #1 /home3/neuwdeni/public_html/dev/app/code/core/Mage/Eav/Model/Entity/Abstract.php(1123): Mage_Eav_Model_Entity_Abstract->_collectSaveData(Object(Mage_Catalog_Model_Product)) #2 /home3/neuwdeni/public_html/dev/app/code/core/Mage/Core/Model/Abstract.php(318): Mage_Eav_Model_Entity_Abstract->save(Object(Mage_Catalog_Model_Product)) #3 /home3/neuwdeni/public_html/dev/pro.php(305): Mage_Core_Model_Abstract->save() #4 {main} thrown in /home3/neuwdeni/public_html/dev/app/code/core/Mage/Core/functions.php on line 245”

    please update if any know this issue

  16. This is a nice tutorial, most of it works fine, however in Magento 1.9.1 the values will not be set for:
    * weight
    * prices

    I guess they are set in a different way

    I have not tested stock data.

  17. Can you please help me how do i add brands in Magento? Currently i am using Biztech extension to add the manufacture but i am not able to add multiple products in that.

    So, i have two questions or i can say i want two help from your side:

    1) How do i add multiple products in Biztech extension?
    2) Is there any other way to add brands and add multiple products in to that brands?

    Thanks in advance.

    Ali

  18. Hi Peter,

    Thanks for the reply. I narrowed the problem down to something else. Specifically, I’m creating custom products with custom attribute set. My attribute set wasn’t assigned correctly, which left required attributes unavailable. Without these attributes, Magento just didn’t show the product in the grids.

    Thanks for the helpful tutorial!

  19. Hi Petar,

    The first line you wrote:
    Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);

    You have used Mage_Core_Model_App::ADMIN_STORE_ID in the argument. Can we even use Mage::app()::ADMIN_STORE_ID
    Just interested to know whether there is any specific reason of using Mage_Core_Model_App instead of Mage::app() in the argument.

    Thanks,
    Uday Sagar.

  20. hmmm… thank for the tutorial, however I’m having a problem implmenting. Perhaps you can help….

    I’m creating products from an extension Im developing. The product is created, however it doesn’t show up under the products grid or my custom grid. I can only see the product by navigating to the Category and clicking the Product tab. Once there, I see the product name and price are not set (however my code is setting these values before save).

    Any suggestions?

  21. Can you let me know that How can i create configurable product by code(script)?

    Thanks in advance

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <blockquote cite=""> <code> <del datetime=""> <em> <s> <strike> <strong>. You may use following syntax for source code: <pre><code>$current = "Inchoo";</code></pre>.

Tell us about your project

Drop us a line. We'd love to know more about your project.