Search code examples
phpmagento

Get custom attribute from product in Magento 1.9


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,


Solution

  • 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?