5

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?

  • Hey @Alex..did you found any solution for this?...If yes, then let me know please... – Yudi Dec 16 '16 at 11:02
  • Hey @Yudi - I eventually got it to work. I'm not too sure if I fixed something or that it was a bug in Magento that got fixed. Either way, I'll dig up my working code and add it as an answer in a moment! – Alex Timmer Dec 16 '16 at 11:05
  • Thanks for quick response. and i am waiting for the answer....:) – Yudi Dec 16 '16 at 11:07
  • @Yudi ; did you get the module working, or do you need the layout of that aswell? – Alex Timmer Dec 16 '16 at 11:08
  • 1
    @Alex...Dude...Its working now.... The foult was only version..when i changed its version to 2.0.1 its started working. Thanks Cheers... – Yudi Dec 16 '16 at 13:46
4

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

  • Does that work with flat tables enabled and disabled?, Don't think so – diazwatson Jan 26 '18 at 17:08
0
$category_id = 20;
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$_category = $objectManager->create('Magento\Catalog\Model\Category')->load($category_id);  
print($_category->getData('custom_attribute'));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.