0

With a fresh install of Magento 1.9.3.8 I am trying to add products programmatically.

It is adding the products , and I can see them in the product listing.

  • It is not generating any URL rewrites
  • The code is not generating any errors or warnings
  • If I enter the product and save it again , the URL rewrite is generated and the product appears fine.

I want to know how to generate a new product and it save correctly. Thanks so much for your time.

require_once '../../app/Mage.php';
Mage::setIsDeveloperMode(true);
ini_set('display_errors', 1);
umask(0);
Mage::app('admin');
$newStoreId = Mage_Core_Model_App::ADMIN_STORE_ID;
Mage::app()->setCurrentStore(Mage::getModel('core/store')->load($newStoreId));

$targetProduct = Mage::getModel('catalog/product');
$targetProduct->load($sourceProduct['entity_id']);

$productAttributes = getProductAttributes($sourceProduct);
$targetProduct->addData($productAttributes);
$targetProduct->setAttributeSetId(4);
$targetProduct->save();
  • Maybe You need to do reindex after Adding New Products Programmatically. – Emipro Technologies Pvt. Ltd. Apr 24 '18 at 10:17
  • Yes, all that has been done. Cache disabled , indexes reindexed a number of times. Thanks . – Martin Thompson Apr 24 '18 at 11:48
  • You can save your attribute with the following code : $product->setData('my_attribute','my_value'); $product->getResource()->saveAttribute($product, 'my_attribute'); – Kozame Apr 24 '18 at 14:04
  • you need to check this : inchoo.net/magento/programming-magento/… – Dhiren Vasoya Apr 24 '18 at 14:06
0

Thanks for your Feedback and thankyou to Dhiren Vasoya. I had seen this post from Inchoo before , but I worked through it to see which part I was missing.

I think it is important to note that you don't have to set the object using

$product->setSomeAttribute()

You can populate an associative array and then assign that which makes it more flexible. The specific issue I was having here was because the website id wasn't set ( and I guess you could set a specific website id different to 1 if appropriate ) for example:

$productAttributes['someAttribute'] = myAttributeValue;
$productAttributes['someAttribute2'] = myAttributeValue2;
$targetProduct->addData($productAttributes);
//Without the next line the product is created but no url rewrites are created
$targetProduct->setAttributeSetId(4);  
$targetProduct->setWebsiteIds(array(1))
$targetProduct->save();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.