Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get custom attribute from product in Magento 1.9

Tags:

php

magento

I'm trying to fetch some product data based on the products SKU. This is working, but I also need to get a custom added attribute at the same time, named 'sku_supplier'. Is this possible?

This is what I got:

require $_SERVER['DOCUMENT_ROOT'] . "/app/Mage.php";
Mage::app();

$sku = '748547';

$products = Mage::getResourceModel('catalog/product_collection');
$products->addAttributeToSelect('*');
$products->addAttributeToFilter('visibility', array('neq' => 1));
$products->addAttributeToFilter('status', 1);
$products->addAttributeToFilter('sku', $sku);
$products->setCurPage(1)->setPageSize(1);
$products->load();

if ($products->getFirstItem()) {
    $product       = $products->getFirstItem();
    $strProdName   = $product->getName();
    $strProdSku    = $product->getSku();
    $strProdSkuSup = $product->getSku_Supplier(); // <= I want to show this
}else{
    $addError          = 'true';
    $addErrorMessage[] = 'Error...';    
}

Thanks in advance,

like image 553
Alldo Avatar asked Jan 15 '15 08:01

Alldo


2 Answers

Just remove the underscore:

$strProdSkuSup = $product->getSkuSupplier();  
$strProdSkuSup = $product->getData('sku_supplier'); //alternative 

Magento translates snake_case into camelCase when you want to use the magic getters; ie. an attribute with the attribute code cool_custom_attribute would translate into coolCustomAttribute, i.e. $product->getCoolCustomAttribute().

Edit:

You might need to load a product model as sometimes I've experienced that not all custom attributes are attached when you pull it out of a collection (intended for performance reasons I guess). Something like:

$_product = Mage::getModel('catalog/product')->load($product->getId());
$strProdSkuSup = $_product->getSkuSupplier();  

Also, did you know that there's a dedicated StackExchange site for Magento?

like image 183
rdiz Avatar answered Nov 16 '22 22:11

rdiz


Use this

$strProdSkuSup = $product->getSkuSupplier();

Instead of

$strProdSkuSup = $product->getSku_Supplier(); 
like image 21
mjdevloper Avatar answered Nov 17 '22 00:11

mjdevloper