Magento 2 - How to get attribute of product?

Best practice in magento is to do it via xml.

To get a standard attribute you do something like this in catalog_product_view.xml for example:

<referenceContainer 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>
</referenceContainer>

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'll use the same default php code for any attribute and you'll have to change it only once if needed.


Another way, for the custom attributes: we can simply get the value by using getCustomAttribute()

if (null !== $product->getCustomAttribute('your_custom_attribute')) {
   echo $product->getCustomAttribute('your_custom_attribute')->getValue();
}

I had solution for my issue:

$product = $this->productRepository->getById($product);
$attr = $product->getData('status');