Displaying Custom attribute in Product LIST PAGE, and Product Details page Under my Price attribute

3k Views Asked by At

I have created a custom attribute named cloth material, and i want to display it in my Product LIST PAGE, and Product Details page Under my Price.

Can someone suggest me how to achieve it? The current blog posts are out dated. I am using Magento 2.3.3.

I also need to do it programmatically. When i do it by selecting Display on store catalog, it displays it under more details.

1

There are 1 best solutions below

1
On BEST ANSWER

First, create catalog_product_view.xml in your custom theme. (If already there, then modify this file)

app/design/frontend/Vendor/theme/Magento_Catalog/layout/catalog_product_view.xml and add the below code in this file:

<?xml version="1.0" ?>
 <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceContainer name="product.info.main">
           <block class="Magento\Catalog\Block\Product\View" name="cloth.material" template="Magento_Catalog::view/cloth_material.phtml" after="product.info.price"/>
        </referenceContainer>
    </body>
</page>

Now create cloth_material.phtml and add the below code in this file:

app/design/frontend/Vendor/theme/Magento_Catalog/templates/product/view/cloth_material.phtml and add the below code in this file:

<?php
   $_product = $block->getProduct();
   // First method
   $attribute_value = $_product->getResource()->getAttribute('your_attribute_code')->getFrontend()->getValue($_product);
   // second method
   $attribute_value = $_product->getAttributeText('your_attribute_code');
?>