Magento 2 - How to get custom attribute value without calling Product->load() first

Published Saturday, October 14, 2017

If you'd like to access a custom attribute, but don't want to call the resource-intensive Product::load() method beforehand, you can grab the value with the method below:

 
  1Magento\Catalog\Model\ResourceModel\AbstractResource::getAttributeRawValue($product_id, $attribute_code, $store_id);
 

Example: [copy]

 
  1$value = $product->getResource()->getAttributeRawValue($product->getId(), 'attribute_code', $product->getStoreId());
 

This returns the raw value, so for a multi-select you'll get a numeric value, like 52.

To turn that into the text value, use:

 
  1$product->getResource()->getAttribute('attribute_code')->getSource()->getOptionText($value);
 

Example with Magento 2.2.0 Sample Data: [copy] [hide]

  1// For this example, I am using Product ID 1 ("Joust Duffle Bag") and set the bag color to orange in the admin.
  2
  3$value = $product->getResource()->getAttributeRawValue($product->getId(), 'color', $product->getStoreId());
  4$text = $product->getResource()->getAttribute('color')->getSource()->getOptionText($value);
  5
  6echo "Color     : ".$value."\n"; // outputs '56'
  7echo "Color     : ".$text."\n";  // outputs 'Orange'
  8
  9// Alternatively, once you have the value, you can set it and call getAttributeText() for the text value
 10
 11$product->setColor($value);
 12echo "Color     : ".$product->getAttributeText('color')."\n"; // outputs 'Orange'