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!