I have created a custom category attribute .The attribute is showing in category section and the data is saved in database .I want to retrieve the value of the category attribute i need it in menu. (Magento 2).

It depends on what you are updating with that attribute . For example if you want to rename the category name with your attribute , you can create a Plugin for override the category name , and adding the new category name in the form created.

In this case create this files in your module:

app/code/Your/Module/etc/frontend/di.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\Catalog\Model\Category">
        <plugin name="PluginName" type="Your\Module\Plugin\AfterCategoryName" sortOrder="1" />
    </type>
</config>

app/code/Your/Module/Plugin/AfterCategoryName.php

   use Magento\Catalog\Model\CategoryFactory;

   class AfterCategoryName
   {
    protected $categoryModel;

    /**
     * AfterCategoryName constructor.
     * @param CategoryFactory $categoryFactory
     */
    public function __construct(CategoryFactory $categoryFactory)
    {
        $this->categoryModel = $categoryFactory;
    }

    /**
     * @param \Magento\Catalog\Model\Category $categoryNew
     * @param $result
     * @return mixed
     */
    public function afterGetName(\Magento\Catalog\Model\Category $categoryNew, $result)
    {
        $category = $this->categoryModel->create();
        $category->load($categoryNew->getId());
        $newCategoryName = $category->getData('your_attribute');

        if (!empty($newCategoryName)) {
            return $newCategoryName;
        }
        return $result;
    }
    }
  • i have creted id attrubute because i want to give id on menu achor – aaaa Dec 7 at 11:53

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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