Friday, November 21, 2014

Magento get product and related products by ID or SKU

Get product by product ID:

$_productId = 166;
$_product = Mage::getModel('catalog/product')->load($_productId);

Get product by product SKU:

$_sku = 'logitechcord';
$_product = Mage::getModel('catalog/product')->loadByAttribute('sku', $_sku);

Get product ID by product SKU:

$_sku = 'logitechcord';
$_catalog = Mage::getModel('catalog/product');
$_productId = $_catalog->getIdBySku($_sku);

Get related products by product ID:

$_relatedProductsId = $_product->getRelatedProductIds();

$relatedProducts=array();
$i=0;

foreach($_relatedProductsId as $relatedProductId)
{
  $_tmpObj = Mage::getModel('catalog/product')->load($relatedProductId);
  $relatedProducts[$i] = $_tmpObj->getName()
    . ' ' . $_tmpObj->getPrice() . ' ' . $_tmpObj->getWeight() . ' ' . $_tmpObj->getDescription()
    . ' ' . $_tmpObj->getImage()
    . ' ' . $_tmpObj->getSmallImage()
    . ' ' . $_tmpObj->getThumbnail()
    . ' ' . $_tmpObj->getImageUrl()
    ;

  $i++;
}

No comments: