In this blog, we will explain how to display custom p[roduct attribute value on Magento 2 product page.
Contents
hide
Step -1: Create registration.php file in app\code\Webiators\CustomChange\
1 2 3 4 5 6 7 |
<?php \Magento\Framework\Component\ComponentRegistrar::register( \Magento\Framework\Component\ComponentRegistrar::MODULE, 'Webiators_CustomChange', __DIR__ ); |
Step -2: Create module.xml file in app\code\Webiators\CustomChange\etc
1 2 3 4 5 6 |
<?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd"> <module name="Webiators_CustomChange" setup_version="1.0.0"/> </config> |
Step -3: Create CustomProductAttribute.php file in app\code\Webiators\CustomChange\Block\Catalog\Product\View
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
<?php namespace Webiators\CustomChanges\Block\Catalog\Product\View; use Magento\Framework\View\Element\Template\Context; class CustomProductAttribute extends \Magento\Framework\View\Element\Template { public function __construct( \Magento\Framework\View\Element\Template\Context $context, \Magento\Framework\Registry $registry, array $data = [] ) { $this->_coreRegistry = $registry; parent::__construct($context,$data); } /** * @return Product */ public function getCurrentProduct() { return $this->_coreRegistry->registry('product'); } } |
Step -4: Create layout file catalog_product_view.xml in app\code\Webiators/CustomChanges/view/frontend/layout
1 2 3 4 5 6 7 8 9 10 11 |
<?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="content"> <referenceBlock name="product.info.main"> <block class="Webiators\CustomChanges\Block\Catalog\Product\View\CustomProductAttribute" name="product.info.main.CustomProductAttribute" as="CustomProductAttribute" after="-" template="Webiators_CustomChanges::catalog/product/view/customattribute.phtml"/> </referenceBlock> </body> </page> |
Step -5: Create templates file customattribute.phtml in app/code/Webiators/CustomChanges/view/frontend/templates/catalog/product/view
1 2 3 4 5 6 7 8 |
<?php $currentProduct = $block->getCurrentProduct(); $customAttrbute = $currentProduct->getCustomAttrbute(); echo $customAttrbute; ?> |
Step -6: Run Command and Check The Result On Product Page
1 2 3 4 5 6 7 8 |
php bin/magento setup:upgrade php bin/magento setup:di:compile php bin/magento setup:static-content:deploy -f en_US php bin/magento cache:flush php bin/magento cache:clean php bin/magento indexer:reindex |
Thank You!
Hit 5 Stars if you find this post helpful
0 (based on 0 Reviews)