kyle
kyle

Reputation: 157

Get magento 2 custom attribute value

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); ?>

Upvotes: 2

Views: 34681

Answers (2)

archana bahadur
archana bahadur

Reputation: 111

The simplest way is,

$customer = $CUSTOMER_OBJECT; // GET customer object
$customer->getCustomAttribute('variable_name')->getValue();

But you need to control $customer->getCustomAttribute('variable_name') is not NULL

Upvotes: 2

Abhinav Kumar Singh
Abhinav Kumar Singh

Reputation: 2325

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');

Upvotes: 3

Related Questions