I don't know exactly what the problem might be for you, but here is a script that worked for me.
But first a remark or 2.
- Calling
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
has no effect in the install scripts.
- You should not create products with the scripts from the sql folder. Use the
data
folder for that. I don't where you placed the code, but in case you put it in the sql
folder move it to data/{resource_name_setup}/data-install-1.0.0.php
(change the version according to your needs).
Now the script that worked for me.
$websiteIds = Mage::getModel('core/website')->getCollection()
->addFieldToFilter('website_id', array('neq'=>0))
->getAllIds();
$product = Mage::getModel('catalog/product');
$product->setStoreId(0); //use this instead of Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
$product->setWebsiteIds($websiteIds);
$product->setTypeId('virtual');
$product->addData(array(
'name' => 'Product name here',
'attribute_set_id' => $product->getDefaultAttributeSetId(), //use the default attribute set or an other id if needed.
'status' => Mage_Catalog_Model_Product_Status::STATUS_ENABLED, //set product as enabled
'visibility' => Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH, //set visibility in catalog and search
'meta_title' => 'Meta title here',
'weight' => 1,
'sku' => 'sku-here',
'tax_class_id' => 2, //could not find a non-hardcoded value for this
'description' => 'Description here',
'short_description' => 'Short description here',
'stock_data' => array( //set stock data
'manage_stock' => 1,
'qty' => 999, //set the qty
'use_config_manage_stock' => 1,
'use_config_min_sale_qty' => 1,
'use_config_max_sale_qty' => 1,
'use_config_enable_qty_increments' => 1,
'in_stock' => 1
),
));
$product->save();
Also don'w wrap your install script in $installer->startSetup()
and $installer->endSetup()
. startSetup
disabled the foreign keys, and you don't want that while adding a product.
Given that the product is already loaded (including this attribute), you can use getData()
instead of the magic getter to be able to use a dynamic attribute code:
$attributeCode = 'custom_attribute_code');
if ($_product->getData($attributeCode) !== null){
echo $_product->getAttributeText($attributeCode);
}
This way you have no unnecessary database queries.
Best Answer