Displaying Custom Attributes in Magento 2 Product List and Details Pages
In this guide, we’ll walk you through the process of displaying custom attributes created for your Magento 2 storefront, specifically focusing on the “Material” attribute under the product price section.
Understanding Your Scenario
You’ve already created a new attribute called “Material” and want it to be displayed prominently:
- In the Product List page.
- Underneath the product price in the Product Details page.
You prefer to handle this programmatically rather than relying solely on admin settings. Let’s break down the solution into two main steps.
Step 1: Define the Attribute Set
First, ensure your custom “Material” attribute is part of an appropriate attribute set. For clothing products:
- Go to Stores > Attributes > Attribute Set.
- Click on the desired set (e.g., Clothing).
- In the General Information section, find the ‘Customizable Options’ tab and click it.
- Add your “Material” attribute to this list if it’s not already included.
Step 2: Modify Product Listing and Details Pages
Step 2A: Product List Page
Navigate to the file responsible for the product listing template:
app/design/frontend/{Vendor}/{Theme}/Magento_Catalog/templates/product/list.phtml
Add the following code just before the </h3> section that displays the product name:
<?php if ($_product->getMaterial()): ?>
<div class="material-label"><?= __('Material') ?>: <?= $_product->getMaterial() ?></div>
<?php endif; ?>
This snippet will display a “Material” label followed by the value of this attribute for each product in the list.
Step 2B: Product Details Page
For the details page, locate and modify this file:
app/design/frontend/{Vendor}/{Theme}/Magento_Catalog/templates/product/view.phtml
Find the <div class="price-box"> section where the price is displayed. Just above it, add the following code:
<?php if ($_product->getMaterial()): ?>
<div class="additional-price-info">
<?= __('Material') ?>: <?= $_product->getMaterial() ?>
</div>
<?php endif; ?>
This will insert your custom “Material” attribute right beneath the product price.
Step 2C: Ensuring Data Population
If you haven’t populated this attribute yet, ensure to do so in the store admin interface (Stores > Products). Assign a value for each product under the “Material” field.
Conclusion and Next Steps
You’ve now successfully integrated your custom “Material” attribute into both the Product List and Details pages programmatically. This approach ensures consistent display across all products.
Remember, always use child themes to override core files as this method avoids conflicts during Magento updates.
For more detailed guides on theme development and configuration in Magento 2, I recommend checking out our extensive resources at LaravelCompany.com.