Magento update product programmatically
Magento update product programmatically :Working with magento we sometimes need to update the products programmatically instead of updating the product from magento admin. Mage::getModel(‘catalog/product’) is used to load the product object and then set the new value which you want to update. In this tutorial we are going to cover various scenarios with example.
Magento update product programmatically
Suppose we have product id and Let us update product name, description & sku as below-
Magento update product programmatically:
public function updateProduct(){ try{ $productId = 100; $product = Mage::getModel("catalog/product")->load($productId); $product->setStatus(1); $product->setName('Test Product'); $product->setSku('test-sku'); $product->setDescription("This is test product description."); $product->setShortDescription("This is short description of product."); $product->save(); }catch (Exception $e) { Mage::logException($e->getMessage()); } } |
The above example loads the product id with 100 and updates the product name, sku, description and short description.
More Examples
Let us have more examples related to updating the products.
magento update product attribute programmatically
Here is another example to update the product’s attribute.
magento update product attribute value programmatically:
public function updateProduct(){ try{ $productId = 100; $product = Mage::getModel("catalog/product")->load($productId); $attrCode = 'my_attr'; $attrVal = "someVal"; $product->setData($attrCode, $attrVal) ->getResource() ->saveAttribute($product, $attributeCode); }catch (Exception $e) { Mage::logException($e->getMessage()); } } |
The above example will update the attribute my_attr with new value $attrVal. Thus you can update any attribute of product.
Magento update product Quantity programmatically
Magento update product Quantity programmatically:
public function updateProduct(){ try{ $productId = 100; $product = Mage::getModel("catalog/product")->load($productId); $product->setQty(99); $product->save(); }catch (Exception $e) { Mage::logException($e->getMessage()); } } |
The above example loads the product and updates the quantity.
Advertisements