Magento 2 – Call Custom Attribute in PHTML File

custom-attributesmagento2

I want to display some text after product price. For example $35 per kg. this text "per kg" I want to append on some products which I am selling on kg basis.

I have created a custom attribute with textfield. I have inserted value per kg into that attribute and assigned with the product I want it to be displayed.

Now my problem is I am not getting any way to call this custom attribute to append to price on frontend. I want this text to be displayed on both category and display page.

I am trying to edit:
vendor\magento\module-catalog\view\base\templates\product\price\amount

I can display custom text by echo but not getting any way to call that custom attribute. code of custom attribute is per kg.

Best Answer

First of all. Don't edit the files in vendor. These will be overwritten when you do bin/magento setup:upgrade. It's a better practise to put your custom theme in app/design/frontend/. Check Magento's guide: http://devdocs.magento.com/guides/v2.0/frontend-dev-guide/themes/theme-create.html

About your attribute, in stead of a text-field you could use a 'yes/no' input type. It will output 1 or 0.

You can get an attribute with:

$_product->getData('attribute_label')

So in your .phtml file you could do something like this:

$attr = $_product->getData('price_per_kg');

if($attr == 1) {
    echo __('Price per kg');
};
Related Topic