
Product information drives purchasing decisions. Magento 2 stores run into situations where default product fields aren't enough. Custom attributes fill this gap. They store extra product details like materials, dimensions, or warranty information.
Getting these custom values displayed requires coding work. Different store sections need different approaches. Product pages, cart sections, and checkout areas each have their own methods. This guide covers practical ways to retrieve and show custom product attribute values across your Magento 2 store.
Understanding Product Attributes in Magento 2
Magento 2 handles product data through attributes. Standard attributes cover basics - name, SKU, price, description. Custom attributes extend this system. Store owners create them for specific business needs.
Consider a furniture store. Standard attributes won't cover wood type, finish options, or assembly requirements. Custom attributes handle these details. They make product pages more informative and help customers choose better.
Cart pages already load certain attributes automatically. The system includes sku, type_id, name, status, visibility, price, weight, url_path, url_key, thumbnail, small_image, tax_class_id, special_from_date, special_to_date, special_price, cost, and gift_message_available in quote data.
Custom attributes need manual configuration. The method depends on where you want them shown. Product detail pages use different techniques than cart implementations.
Method 1: Get Custom Attribute Value Using Product Repository
The most reliable approach involves using Magento's Product Repository interface, ensuring proper data retrieval while maintaining compatibility with Magento's architecture.
<?php
namespace Company\Module\Helper;
use Magento\Framework\App\Helper\AbstractHelper;
use Magento\Catalog\Model\Product\Attribute\Repository;
class Data extends AbstractHelper
{
private $productAttributeRepository;
public function __construct(
\Magento\Framework\App\Helper\Context $context,
Repository $productAttributeRepository
) {
parent::__construct($context);
$this->productAttributeRepository = $productAttributeRepository;
}
/**
* Get attribute options by attribute code
*
* @param string $attrCode
* @return array|false
*/
public function getAttributeOptions(string $attrCode)
{
try {
$attribute = $this->productAttributeRepository->get($attrCode);
return $attribute->getOptions();
} catch (\Exception $e) {
$this->_logger->error($e->getMessage());
return false;
}
}
}
Method 2: How to Get Product Custom Attribute Value on Product Detail Page
Getting custom attribute values directly on product detail pages requires accessing the current product object. This method works effectively for displaying additional product specifications.
<?php
namespace Company\Module\Helper;
use Magento\Framework\App\Helper\AbstractHelper;
use Magento\Eav\Model\AttributeManagement;
use Magento\Catalog\Model\Product;
class Data extends AbstractHelper
{
private $attributeManagement;
public function __construct(
\Magento\Framework\App\Helper\Context $context,
AttributeManagement $attributeManagement
) {
parent::__construct($context);
$this->attributeManagement = $attributeManagement;
}
/**
* Get all attributes for attribute set
*
* @param int $attributeSetId
* @return array
*/
public function getAttributesBySet(int $attributeSetId): array
{
try {
$attributes = [];
$attributeCollection = $this->attributeManagement->getAttributes(
Product::ENTITY,
$attributeSetId
);
foreach ($attributeCollection as $attribute) {
$attributes[] = $attribute->getData();
}
return $attributes;
} catch (\Exception $e) {
$this->_logger->error($e->getMessage());
return [];
}
}
}
Method 3: Get Custom Attribute Value in Product Detail Page Magento 2
Another approach involves using the attribute management system to retrieve attributes according to the attribute set ID:
<?php
namespace Company\Module\Helper;
use Magento\Framework\App\Helper\AbstractHelper;
use Magento\Eav\Model\AttributeManagement;
use Magento\Catalog\Model\Product;
class Data extends AbstractHelper
{
private $attributeManagement;
public function __construct(
\Magento\Framework\App\Helper\Context $context,
AttributeManagement $attributeManagement
) {
parent::__construct($context);
$this->attributeManagement = $attributeManagement;
}
/**
* Get all attributes for attribute set
*
* @param int $attributeSetId
* @return array
*/
public function getAttributesBySet(int $attributeSetId): array
{
try {
$attributes = [];
$attributeCollection = $this->attributeManagement->getAttributes(
Product::ENTITY,
$attributeSetId
);
foreach ($attributeCollection as $attribute) {
$attributes[] = $attribute->getData();
}
return $attributes;
} catch (\Exception $e) {
$this->_logger->error($e->getMessage());
return [];
}
}
}
Method 4: How to Get Product Custom Attribute in Cart Page
Displaying custom product attributes in the shopping cart requires specific configuration to load attributes that are not available by default in Magento 2 quote data.
Step 1: Create catalog_attributes.xml file under your module's etc directory.
app/code/Vendor/Extension/etc/catalog_attributes.xml
Step 2: Add the following code to catalog_attributes.xml
<?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="custom_attribute"/>
<attribute name="another_attribute"/>
</group>
</config>
Step 3: Copy default.phtml from the following path
vendor/magento/module-checkout/view/frontend/templates/cart/item/default.phtml
to your theme, then add the following line to display your attribute:
<?php echo $product->getCustomAttribute(); ?>
Step 4: Access the attribute value in cart using:
$_item->getProduct()->getProductAttributeCode()
Step 5: Refresh the cache to apply changes.
Advanced Implementation for Cart Attributes
For more complex cart attribute display requirements, implement the following approach:
<?php
/** @var \Magento\Quote\Model\Quote\Item $_item */
$product = $_item->getProduct();
$attributeCode = 'custom_attribute';
// Safe attribute value retrieval
$attributeValue = $product->getData($attributeCode);
// For select/dropdown attributes
$attributeText = $product->getAttributeText($attributeCode);
if ($attributeText || $attributeValue) {
$displayValue = is_array($attributeText)
? implode(', ', $attributeText)
: ($attributeText ?: $attributeValue);
?>
<div class="cart-item-attribute">
<strong><?= $block->escapeHtml(__('Custom Attribute')) ?>:</strong>
<span><?= $block->escapeHtml($displayValue) ?></span>
</div>
<?php
}
This approach allows displaying custom attributes with proper formatting and styling within the cart section.
Getting Dropdown Attribute Options
When working with dropdown or select type attributes, retrieving the available options requires a specific implementation:
<?php
namespace Company\Module\Helper;
use Magento\Framework\App\Helper\AbstractHelper;
use Magento\Catalog\Model\Product\Attribute\Repository;
class AttributeOptions extends AbstractHelper
{
private $productAttributeRepository;
public function __construct(
\Magento\Framework\App\Helper\Context $context,
Repository $productAttributeRepository
) {
parent::__construct($context);
$this->productAttributeRepository = $productAttributeRepository;
}
/**
* Get attribute options with labels and values
*
* @param string $attributeCode
* @return array
*/
public function getAttributeOptions(string $attributeCode): array
{
try {
$attribute = $this->productAttributeRepository->get($attributeCode);
$options = $attribute->getOptions();
$result = [];
foreach ($options as $option) {
if ($option->getValue()) {
$result[] = [
'value' => $option->getValue(),
'label' => $option->getLabel()
];
}
}
return $result;
} catch (\Exception $e) {
$this->_logger->error($e->getMessage());
return [];
}
}
}
Object Manager Method (Quick Testing Only)
For quick testing purposes, the Object Manager provides immediate access to product data. However, this method should never be used in production environments:
<?php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$product = $objectManager->create('Magento\Catalog\Model\Product')->load($productId);
$customAttributeValue = $product->getData('attribute_code');
// For attribute text values
$attributeText = $product->getAttributeText('attribute_code');
Best Practices for Custom Attribute Implementation
Proper Dependency Injection: Always use constructor dependency injection instead of Object Manager in production code. This ensures better performance, maintainability, and follows Magento coding standards.
Error Handling: Implement comprehensive try-catch blocks when retrieving attribute values to prevent store crashes due to missing attributes or products.
Attribute Validation: Verify attribute existence and product availability before attempting to retrieve values, especially when dealing with optional custom attributes.
Performance Optimization: Custom attribute retrieval can impact page load times. Consider implementing caching mechanisms for frequently accessed attributes and avoid loading unnecessary data.
Store View Considerations: Remember that attribute values may vary across different store views. Ensure the proper store context is maintained when retrieving attribute values.
Troubleshooting Common Issues
Attribute Values Not Displaying: Verify that the attribute is properly assigned to the correct attribute set and has appropriate visibility settings configured in the admin panel. Check if the attribute has been saved with actual values for the specific product.
Empty or Null Values: Custom attributes that haven't been set for specific products will return null or empty strings. Implement proper validation to handle these cases gracefully.
Cart Attribute Loading Issues: When custom attributes don't appear in the cart, ensure the catalog_attributes.xml file is properly configured and the cache has been cleared after implementation.
Performance Degradation: Large stores with numerous custom attributes may experience slower page loads. Consider implementing selective attribute loading and utilizing Magento's built-in caching mechanisms.
Attribute Set Compatibility: Different products may belong to different attribute sets. Ensure your code handles cases where specific attributes may not be available for all products.
Data Type Handling: Custom attributes can contain various data types, including text, numbers, dates, and boolean values. Implement proper type checking and conversion when displaying these values.
Advanced Attribute Management with Extensions
While manual coding provides flexibility, managing numerous custom attributes across different store sections can become complex. Professional extensions streamline this process significantly.
The Magento 2 Custom Attributes Extension offers comprehensive attribute management capabilities, allowing store administrators to create unlimited customer attributes easily without extensive coding knowledge. This Customer Attributes for Magento 2 extension provides:
-
An easy Graphical User Interface to make the process easier and attractive
-
Unlimited Customer Attributes creation capabilities
-
Various Input Validation for Each Attribute
-
Enhanced user experience with personalized customer feeds
-
Better Management of Data collected from customers
-
A separate section to manage the information given by customers
The MageDelight Customer Attributes Magento 2 Extension proves particularly valuable for stores requiring extensive customization without dedicating significant development resources, offering one of the smart ways to add attribute fields at various places.
Conclusion
Retrieving custom product attribute values in Magento 2 requires understanding various implementation approaches depending on the specific use case. Whether displaying attributes on product detail pages, cart sections, or other store areas, proper coding techniques ensure reliable functionality.
For stores requiring extensive attribute management capabilities, the Magento 2 Custom Attributes Extension provides efficient solutions that reduce development time while offering advanced features. The Customer Attributes for Magento 2 extension, with its Easy Graphical User Interface and ability to create Unlimited Customer Attributes, represents a smart solution for enhanced customer data collection.
The key lies in choosing the right approach based on technical requirements, maintenance capabilities, and long-term scalability needs. Regular testing and following Magento coding standards ensure custom attribute implementations remain stable across platform updates and store modifications.