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:


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.
  3$value = $product->getResource()->getAttributeRawValue($product->getId(), 'color', $product->getStoreId());
  4$text = $product->getResource()->getAttribute('color')->getSource()->getOptionText($value);
  6echo "Color     : ".$value."\n"; // outputs '56'
  7echo "Color     : ".$text."\n";  // outputs 'Orange'
  9// Alternatively, once you have the value, you can set it and call getAttributeText() for the text value
 12echo "Color     : ".$product->getAttributeText('color')."\n"; // outputs 'Orange'