comment 0
/ wsagen

Retrieving Custom Product Attribute Values in M2

When you have custom product attributes in extension code, at some point you may need to access those values using items in the cart. To do this you can take the following approach

//Retrieve id of product
$productID = $item->getProduct()->getId();

//load the product
$product = $this->objectManager->create('Magento\Catalog\Model\Product')->load($productID);

//retrieve the value of your attribute
$myAttributeValue = $product->getData('my_custom_attribute');

Loading the product object explicitly is a pretty expensive process, as such Magento have implemented a way to directly access attribute values without this explicit load.

You’ll need to do the following in M2:

  1. Create catalog_attributes.xml in your extension that lists your attributes (look for examples in Magento 2 for full file syntax)  
    .... <group name="quote_item">
    <attribute name="my_custom_attribute"/>
    </group> ....
  2. Use  $item->getProduct()->getData('my_custom_attribute') to retrieve your attribute value

Note: An identical process is available in Magento 1.x, using config.xml and the <product_attributes> section in Step 1.

Leave a Reply

Your email address will not be published. Required fields are marked *