This is a quick tutorial for developer on how to load products by SKU, ID, attribute of products in Magento. The tutorial can be applied for loading single product or multiple products.
Load product by Product ID
Normally, we load product by ID. Let’s say that product ID is 88, you can use the following code in app/code/core/Mage/Catalog/Model/Product.php :
1 2 3 | $_productId = '88'; $_product = Mage::getModel('catalog/product')->load($_productId); print $_product->getName() // display product name |
Load product by SKU
In case you want to load product/product by its attribute, for example SKU, you can use the following code in app/code/core/Mage/Catalog/Model/Product.php :
1 2 3 | $_sku = 'leathershoes'; $_product = Mage::getModel('catalog/product')->loadByAttribute('sku',$_sku); print $_product->getName(); // display product name |
Alternatively, you can also use this code to load product by SKU
1 2 3 4 | $_sku = 'leathershoes'; $_catalog = Mage::getModel('catalog/product'); $_productId = $_catalog->getIdBySku($_sku); $_product = Mage::getModel('catalog/product')->load($_productId); |
You can change attribute as you want by replacing SKU variable in the example.
Load multiple products
Load multiple product by Product ID
1 2 3 4 5 6 | $productIds = array(3, 21, 24, 42, 74); // insert product IDs you want to load $attributes = Mage::getSingleton('catalog/config')->getProductAttributes(); $collection = Mage::getModel('catalog/product') ->getCollection() ->addAttributeToFilter('entity_id', array('in' => $productIds)) ->addAttributeToSelect($attributes); |
Similarly, you can load multiple product by Product attribute, like SKU
1 2 3 4 5 6 | $productSku = array('234', '267', '4523', 'Leather shoes', 'skin care'); // insert product SKU here $attributes = Mage::getSingleton('catalog/config')->getProductAttributes(); $collection = Mage::getModel('catalog/product') ->getCollection() ->addAttributeToFilter('sku', array('in' => $productSku)) ->addAttributeToSelect($attributes); |
Conclusion
The examples above will help you load products by ID, SKU, you can customize the code for other attributes according to your requirement.
1 Comment
Thanks for sharing!
For interest, if you want to search items by SKU quickly and order in bulk, you can use an extension called Magento Wholesale Fast Order, here is demo: http://bsscommerce.com/magento-wholesale-fast-order.html
Hope it helps!