Magento – Magento 2 How to get custom category attribute on frontend

category-attributemagento2

I have created a new category attribute using a setup script and now it is showing on the backend and assigned values (it is just a boolean attribute). the attribute name on EAV entity table is is_home_category .And now I'm trying to get its values on frontend

$categories = $this->getStoreCategories(true, true, true);

foreach ($categories as $category):
   echo $category->getIsHomeCategory()
endforeach;

But it returns nothing , could someone help me

Best Answer

Proper way is to in the Install/Upgrade script:

    $eavSetup->addAttribute(
        \Magento\Catalog\Model\Category::ENTITY,
        'my_custom_attribute',
        [
            // ...
            'used_in_product_listing' => true, // for category pages
            'visible_on_front' => true, // for frontend??
            'is_used_in_grid' => true, // for category pages
            'is_visible_in_grid' => true // for category pages
        ]
    );

also on the collection do:

$collection->addAttributeToSelect('my_custom_attribute')

and then in the template you can just call:

$category->getMyCustomAttribute()
// or
$category->getData('my_custom_attribute');

If still not work run below command:

php bin/magento in:reindex
Related Topic