Question

How to add product from frontend with custom attributes ? I have this code form another stack question

//$product = Mage::getModel('catalog/product');
$product = new Mage_Catalog_Model_Product();
echo time();
// Build the product
$product->setAttributeSetId(9);// #4 is for default
$product->setTypeId('simple');

$product->setName('Some cool product name');
$product->setDescription('Full description here');
$product->setShortDescription('Short description here');
$product->setSku(time());
$product->setWeight(4.0000);
$product->setStatus(1);
$product->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH);//4
print_r(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH);

$product->setPrice(39.99);// # Set some price
$product->setTaxClassId(0);// # default tax class

$product->setStockData(array(
'is_in_stock' => 1,
'qty' => 99999
));

$product->setCategoryIds(array(27));// # some cat id's,

$product->setWebsiteIDs(array(1));// # Website id, 1 is default

//Default Magento attribute

$product->setCreatedAt(strtotime('now'));


//print_r($product);
try {
    $product->save();
    echo "Product Created";
}
catch (Exception $ex) {
    //Handle the error
    echo "Product Creation Failed";
}

But i have custom attributes also , and how to add them from that code.

Was it helpful?

Solution

For each attribute you have you need to call:

$product->setData('attribute_code_here', 'Value here');

[Edit]

For yes/no attributes do it like this:

$product->setData('attribute_code_here', 1); //1 for Yes, 0 for No

For multiple selects

$product->setData('attribute_code_here', "4,6,12"); //the ids of the values concatenated by comma.

OTHER TIPS

First add a product with all attributes per hand into your Magento, so that you can figure out how Magento uses them. Load that Product and print_r all variables, then use them to save a new product.

$_product = Mage::getModel('catalog/product')->load('PRODUCT ID');

Zend_Debug::dump($_product);

Get All the Attributes you need to save a new Product and do that:

$_product = Mage::getModel('catalog/product');
$_product->setYourAttribute('...');
$_product->save();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top