Magento 2.1 – Show Custom Category Attribute on Frontend

categorycustom-attributesmagento-2.1

I added a custom category attribute via a module as this tutorial shows, that's working fine; the field is shown and saved correctly in the backend. But I can't figure out how to show it on the frontend.

I've added the attribute as a textfield, and it's content is supposed to be shown in a custom .phtml block that gets loaded on the category-view via XML.

I first tried to do it like you'd call a product attribute, i.e.

$_helper = $this->helper('Magento\Catalog\Helper\Output');
$_category = $block->getCategory();
echo $_category->getData('customcatattribute');

But no luck.

Then I found this answer and applied what it says, but still no luck.

Whenever I try to call the field I either get no results and the page works, or the page breaks and stays blank.

This shouldn't be too hard, how can I call my custom category attribute?

Best Answer

Eventually I was able to call the custom attribute in the frontend (in my case an extra category-image) like this:

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$category = $objectManager->get('Magento\Framework\Registry')->registry('current_category');//get current category
$catbgimg = $category->getData('cat_bgimg');

if (!empty($catbgimg)) {
    echo '<img src="' . $catbgimg . '" />';
} else {
    // Something else
}

I know calling the objectManager directly is shunned, but whatever works. If anyone has a better idea, I'd love to hear :)

Edit: I added the module to GitHub: https://github.com/Asitis/m2-CatAtt

Related Topic