Home > OS >  Magento 2.3 get custom category attribute in .phtml file
Magento 2.3 get custom category attribute in .phtml file

Time:01-26

I have created a custom category attribute title_description and is showing on the admin side and I can save data. But when I try to show the value on the frontend using getTitleDescription() it is not showing anything. It is working for default category attributes like getName() and getId(). In my block I have created the function

public function getCurrentCategory()
    {
        $currentCategory = $this->registry->registry('current_category');
        return $currentCategory;
    }

And in .phtml file I am calling

$block->getCurrentCategory()->getTitleDescription()

It works on other pages where I am using a collection of categories and looping through it. But not working when calling an individual category

CodePudding user response:

You can add your custom attribute to Magento's list of attributes that it'll load by default when loading categories.

Create a file called catalog_attributes.xml in the etc folder of your module.

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Catalog:etc/catalog_attributes.xsd">
    <group name="catalog_category">
        <attribute name="title_description"/>
    </group>
</config>

Note that the group is called catalog_category, which is the group for auto-loaded attributes. This file is capable of doing other things as well, which you can learn about here.

CodePudding user response:

You can also try adding

public function getTitleDesc()
{            
    return $this->getCustomAttribute('title_description');            
}

In your block and then call the function. Note you should flush the cache before calling it.

  • Related