Magento 2 Get Product Custom Attribute in Cart Page

Sometime you need to fetch some product attributes in the cart page which are not by default loaded in the Magento 2 quote data.

Below are by default product attribute values which are loaded by Magento. You can get these values without any modification.

File: /vendor/magento/module-sales/etc/catalog_attributes.xml

<attribute name="sku"/>
<attribute name="type_id"/>
<attribute name="name"/>
<attribute name="status"/>
<attribute name="visibility"/>
<attribute name="price"/>
<attribute name="weight"/>
<attribute name="url_path"/>
<attribute name="url_key"/>
<attribute name="thumbnail"/>
<attribute name="small_image"/>
<attribute name="tax_class_id"/>
<attribute name="special_from_date"/>
<attribute name="special_to_date"/>
<attribute name="special_price"/>
<attribute name="cost"/>
<attribute name="gift_message_available"/>

If you want to fetch any product values other than above then you must have to specify these attributes from your custom module. Magento provides a simple way to assign any product attribute values to any specific model like quote, category, product etc. Here we are showing you how to load product attributes to the quote data.

Steps to get product attribute values in the cart page in Magento 2

Step 1: Create catalog_attributes.xml file under your module’s etc directory. E.g., app/code/Dhairvi/Demo/etc/
Step 2: Add the below code to this newly catalog_attributes.xml file.

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Catalog:etc/catalog_attributes.xsd">
    <group name="quote_item">
        <attribute name="product_attribute_code"/>
    </group>
</config>

Step 3: Now you can get this attribute to the cart page like below.

$_item->getProduct()->getProductAttributeCode()

You can review our previous blog Magento 2 system.xml Field Dependency on Multiple Values