Magento 2 – No Access to Custom Attributes in Product Collection

magento2phtml

The Problem:
I am modifying the Magento_Catalog/templates/product/list.phtml and I'm trying to access my custom attribute ku_untetitel.

In the .phtml, I'm using the following code to get the productCollection (magento default):

$_productCollection = $block->getLoadedProductCollection();

And I try this to get my custom attribute:

<span class="description">
    <?php
            if(!empty($_product->getData('ku_untertitel'))):
            echo $_product->getData('ku_untertitel');
        endif;  
    ?>
</span>

When taking a look at the frontend, the HTML is there, but the content is empty, like this:

<span class="description">



</span>

What am I doing wrong here, and why can't I access custom attributes when getting the product Collection trough something else then my own Collection? I suppose the collection doesn't contain much more information then the basic attributes, but not the custom attributes.

How can I modify my files in order to achieve what I want?

Best Answer

First of all, make sure our custom attribute can be used in product listing: STORES > Product Attributes > select your custom attribute > Storefront Properties > Used in Product Listing to Yes

enter image description here

Second, assign our attribute to Attribute Set: STORES > Product Attributes > Attribute Sets

Third, if we take a look at vendor/magento/module-catalog/view/frontend/templates/product/list.phtml, we can see the way how to get product attribute value, e.g: $_helper->productAttribute($_product, $_product->getName(), 'name'). So, we can get our custom attribute like:

$_helper->productAttribute($_product, $_product->getKuUntertitel(), 'ku_untertitel');

Clear Magento Cache and refresh the product listing page.

Related Topic