Get magento 2 custom attribute value

kyle picture kyle · Sep 24, 2017 · Viewed 25.5k times · Source

I am able to display attribute values using the code below BUT if the attribute is empty it just prints out the word "No"

<?php echo $_product->getResource()->getAttribute('c_address')->getFrontend()->getValue($_product); ?>

Answer

Abhinav Kumar Singh picture Abhinav Kumar Singh · Sep 25, 2017

To get the customer attribute,you can use like this:

$customerRepository = $objectManager->get('Magento\Customer\Api\CustomerRepositoryInterface');
$customer = $customerRepository->getById(1);
$cattrValue = $customer->getCustomAttribute('c_address');

To get the product attribute,you can use like this:

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$product = $objectManager->get('Magento\Catalog\Model\Product')->load('YOUR PRODUCT ID');
echo $product->getAttributeText('your_attribut');