MAGENTO 1.X – USEFUL MAGENTO CODE SNIPPETS
Those are many code snippets that could be helpful for you on shell scripts, standalone scripts, or in different situations of your market flow.
- Iterate through all products, and add a prefix on its names:
1234567891011$products = Mage::getModel('catalog/product')->getCollection()->addAttributeToSelect("*")//->addAttributeToFilter('sku', '1161') Just in case you want to work with one product->load();$prefix = "[OFFSET101]";foreach ($products as $_product) {$_product->setData('name', $prefix.$_product->getName());$_product->save();} - Update product attribute according to a particular store (or the default one).
1234// $product->addAttributeUpdate('att_code', 'value', store_id)// Store ID 0 is the default one$product->addAttributeUpdate('visibility', Mage_Catalog_Model_Product_Visibility::VISIBILITY_NOT_VISIBLE, 0); - Move a Category inside another one:
12345678910111213141516$category = Mage::getModel('catalog/category')->load($categoryId);if (!$category) {echo "Provided category child ID doesn't belong to a category";exit;}$categoryParent = Mage::getModel('catalog/category')->load($categoryParentId);if (!$categoryParent) {echo "Provided category parent ID doesn't belong to a category";exit;}Mage::getSingleton('catalog/category_api')->move($categoryId, $categoryParentId);echo "Category \"{$category->getName()}\" moved inside of category \"{$categoryParent->getName()}\""; - Move every product from a category to another one:
1234567891011121314151617181920212223$categoryOrigin = Mage::getModel('catalog/category')->load($categoryOriginId);if (!$categoryOrigin) {echo "Provided category origin ID doesn't belong to a category";exit;}$categoryDestiny = Mage::getModel('catalog/category')->load($categoryDestinyId);if (!$categoryDestiny) {echo "Provided category destiny ID doesn't belong to a category";exit;}$products = Mage::getResourceModel('catalog/product_collection')->setStoreId(Mage::app()->getStore()->getId())->addCategoryFilter($categoryOrigin);foreach ($products as $product) {Mage::getSingleton('catalog/category_api')->removeProduct($categoryOriginId, $product->getId());Mage::getSingleton('catalog/category_api')->assignProduct($categoryDestinyId, $product->getId());}echo count($products) . " Products were moved from \"{$categoryOrigin->getName()}\" to \"{$categoryDestiny->getName()}\""; - Assign product to a category:
12345678# One way to do so, and the most easiest is using category model.Mage::getSingleton('catalog/category_api')->assignProduct($categoryDestinyId, $product->getId());# Second way, is using directly the product model.$categories = array();$categories[] = $row[category_id];$product->setCategoryIds($categories);$product->save() - Remove products from a category:
1234567891011121314151617$categoryId = $this->getArg('category');$category = Mage::getModel('catalog/category')->load($categoryId);if (!$category) {echo "Provided category ID doesn't belong to a category";exit;}$products = Mage::getResourceModel('catalog/product_collection')->setStoreId(Mage::app()->getStore()->getId())->addCategoryFilter($categoryId);foreach ($products as $product) {Mage::getSingleton('catalog/category_api')->removeProduct($categoryId, $product->getId());}echo count($products) . " Products were removed from \"{$categoryOrigin->getName()}\""; - Change base image / small image / thumbnail for a product, between all its gallery images:
12345678910111213141516171819$products = Mage::getModel('catalog/product')->getCollection()->addAttributeToSelect("*")->load();foreach ($products as $_product) {$mediaApi = Mage::getModel('catalog/product_attribute_media_api');$mediaItems = $mediaApi->items($_product->getId());foreach ($mediaItems as $image) {//Set first available image on product image gallery$_product->setData('image', $image['file']);$_product->setData('small_image', $image['file']);$_product->setData('thumbnail', $image['file']);$_product->save();break;}} - Create a custom log file:
1Mage::log('My log entry', null, 'mylogfile.log', true); - Change product stock inventory items data (Qty + Is in stock):
1234567891011private function updateStockQty($sku, $newQty){$product_id = Mage::getModel("catalog/product")->getIdBySku( $sku );$stockItem = Mage::getModel('cataloginventory/stock_item')->loadByProduct($product_id);if ($stockItem->getId() > 0 && $stockItem->getManageStock()) {$stockItem->setQty($newQty);$stockItem->setIsInStock((int)($newQty > 0));$stockItem->save();}} - Display and show apache errors on screen:
12error_reporting( E_ALL );ini_set('display_errors', 'on'); - Get at order from its increment id:
1Mage::getModel('sales/order')->loadByIncrementId('your-increment-id'); - Get orders from increment id starting with (LIKE):
1234567$write = Mage::getSingleton('core/resource')->getConnection('core_read');$result=$write->query("SELECT entity_id FROM `sales_flat_order` WHERE `increment_id` like '".$nakedOrderNumber."%';$row = $result->fetch();if(empty($row)){// No results have been found.} - Format and show a number with 2 decimals and comma separated despite its actual format ( 2 and comma, are examples, you can use whatever you want instead):
123# string number_format ( float $number , int $decimals = 0 , string $dec_point = "." , string$thousands_sep = "," )number_format((float)$myNumber, 2, ',', '') - Get stock information from a product when you are iterating:
1Mage::getModel('cataloginventory/stock_item')->loadByProduct($_product)->getData('is_in_stock'); - Get logged in customer(for frontend purposes):
12345678# get customerMage::getSingleton('customer/session')->getCustomer();# get customer idMage::getSingleton('customer/session')->getCustomer()->getId();# get any customer particular fieldMage::getSingleton('customer/session')->getCustomer()->getData('field-id'); - Load product by attribute:
12345678// Load Magento product by id$product = Mage::getModel('catalog/product')->load($productID);// Load Magento product by sku$product = Mage::getModel('catalog/product')->loadByAttribute('sku', $productSku);// Load Magento product by name$product = Mage::getModel('catalog/product')->loadByAttribute('name', $productName); - Get product ID by SKU:
12$product_sku = 123456; // use your own sku number$product_id = Mage::getModel("catalog/product")->getIdBySku( $product_sku ); - Remove product:
12345678// Register begin of a secure admin environment sectionMage::register('isSecureArea', true);// Load the Magento product by entity_id$product = Mage::getModel('catalog/product')->load($productId);// Delete the product$product->delete(); - Show product parents sku’s from child id:
1234567$parentsIds = Mage::getModel('catalog/product_type_configurable')->getParentIdsByChild(<your_child_id>);foreach($parentsId as $parentId){$parentSku = Mage::getModel('catalog/product')->load($parentId)->getSku();echo "Parent ID: $parentSku \n";} - Load first occurrence of a model object:
123456789# Performant and recommended way$object1 = Mage::getModel('vendor_extension/modelname')->load($value, 'resource_field');# Working with collections (in case you need to apply more filters)$object2 = Mage::getModel('vendor_extension/modelname')->getCollection()->addFieldToFilter('resource_field', array('eq' => $value))->load()->getFirstItem(); - Get Store:
12345678# Get StoreMage::app()->getStore()# Get Store IDMage::app()->getStore()->getId()# Get Store ID by CODEMage::getModel('core/store')->load($storeCode, 'code')->getId() - Iterate through all folder files:
123456789// Get all files inside a folder on media.$files = scandir(Mage::getBaseDir('media') . DS . 'your/folder/inside/');foreach ($files as $file) {// Just work with .csv filesif (strpos($file, ".csv") !== FALSE) {// Do something.}}