SPECIAL OFFER: ENJOY 3 MONTHS OF SHOPIFY FOR $1/MONTH SPECIAL OFFER: ENJOY 3 MONTHS OF SHOPIFY FOR $1/MONTH SPECIAL OFFER: ENJOY 3 MONTHS OF SHOPIFY FOR $1/MONTH SPECIAL OFFER: ENJOY 3 MONTHS OF SHOPIFY FOR $1/MONTH SPECIAL OFFER: ENJOY 3 MONTHS OF SHOPIFY FOR $1/MONTH SPECIAL OFFER: ENJOY 3 MONTHS OF SHOPIFY FOR $1/MONTH SPECIAL OFFER: ENJOY 3 MONTHS OF SHOPIFY FOR $1/MONTH SPECIAL OFFER: ENJOY 3 MONTHS OF SHOPIFY FOR $1/MONTH SPECIAL OFFER: ENJOY 3 MONTHS OF SHOPIFY FOR $1/MONTH SPECIAL OFFER: ENJOY 3 MONTHS OF SHOPIFY FOR $1/MONTH
product-attribute

How to get product attribute in Magento 2

magento you can get the attributes contained in the product added in the admin or the module can get the value contained in that product by. In Vendor/Module/Block/GetAttribute.php

It is required to enable Used in Product Listing to get the value of the attribute by checking if not enabled, select Yes
Admin panel > STORES > Attributes > Product > edit custom attribute > Storefront Properties > Used in Product Listing

<?php
 
namespace Vendor/Module/Block;
 
 
class Index extends \Magento\Framework\View\Element\Template {
    
    /**
     * @var \Magento\Catalog\Model\ProductRepository
     */
    protected $_productRepository;

    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Catalog\Model\ProductRepository $_productRepository, 
        array $data = []) {
        $this->_productRepository  = $_productRepository; 
        parent::__construct($context, $data);
 
    }
 
 
    protected function getAttributeProduct($_product)
    {
        $this->_productRepository->get($_product->getSku());
        // if ($_product->getData('attribute_product')) {  getattribute 2.4.X
        if (!is_null($_product->getAttributeText('attribute_product'))) {
            // get product attribute text
            $_product->getAttributeText('attribute_product');
            // get product attribute value
            $_product->getCustomAttribute('attribute_product')->getValue();
        }
        
    }
    
}

You can get by object Manager

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$productRepository = $objectManager->get('\Magento\Catalog\Model\ProductRepository');
$_product = $block->getProduct(); 
$_product = $productRepository->get($_product->getSku());
if ($_product->getAttributeText('attribute_product') != null){
    echo $_product->getAttributeText('brand');
}

Hope this article will help you in some way, You can see useful articles in the next articles.

Anything you need support from Magento 2 feels free to contact us at Alothemes .

Email: support@alothemes.com