Magento 2: Get product attribute’s select option id,label for configurable product
you can do it same as magento 1,
More information in details, Visit, Get Option id and Label from configurable product
//get option label based on option id from product object
$optionId = 10;
$attr = $_product->getResource()->getAttribute('color');
if ($attr->usesSource()) {
$optionText = $attr->getSource()->getOptionText($optionId);
}
//get option text ex. Red
//get option id based on option label
$attr = $_product->getResource()->getAttribute('color');
if ($attr->usesSource()) {
$option_id = $attr->getSource()->getOptionId("Red");
}
//get option id ex. 10
Best practice in magento is to do it via xml.
To get a standard attribute like brand
you do something like this in catalog_product_view.xml
for example:
<referenceBlock name="product.info.main">
<block class="Magento\Catalog\Block\Product\View\Description" name="product.info.brand" template="product/view/attribute.phtml" before="-">
<arguments>
<argument name="at_call" xsi:type="string">getBrand</argument>
<argument name="at_code" xsi:type="string">brand</argument>
<argument name="css_class" xsi:type="string">brand</argument>
<argument name="at_label" xsi:type="string">none</argument>
<argument name="add_attribute" xsi:type="string">itemprop="brand"</argument>
</arguments>
</block>
</referenceBlock>
This will get the value of an input attribute or textarea. If you have a dropdown you should use the text type, so add this line in the list of arguments:
<argument name="at_type" xsi:type="string">text</argument>
No need to create files or write any php code to get an attribute. This way you will have consistency and use the same attribute.phtml file for all attributes. If something changes you need to change it in one place only.
Worked for me
$_product->getResource()->getAttribute('your_attribute_code')->getFrontend()->getValue($_product);