Thursday, 27 June 2019

Category Custom Attribute Value in magento2

1. Create Block file Attribute.php app/code/Category/CustomAttribute/Block/Attribute.php

<?php
/**
 * Ansar Husain
 * Category_CustomAttribute
 */

namespace Category\CustomAttribute\Block;

use Magento\Catalog\Api\CategoryRepositoryInterface;

/**
 * Class Attribute
 * @package  Category\CustomAttribute\Block
 */
class Attribute extends Template
{


    /**
     * @var Magento\Catalog\Api\CategoryRepositoryInterface
     */
    protected $_categoryRepositoryInterface;

    /**
     * Attribute constructor.
     * @param Template\Context $context
     * @param CategoryRepositoryInterface $categoryRepositoryInterface
     * @param array $data
     */
    public function __construct(
        Template\Context $context,
        CategoryRepositoryInterface $categoryRepositoryInterface,
        array $data = []
     )
    {
        $this->_scopeConfig = $scopeConfig;

        parent::__construct($context, $data);
    }

   public function getCustomAttribute($category_id){

   $category = $this->_categoryRepositoryInterface->get($category_id);
   $customAttributeValue = $category->getCustomAttribute('custom_attribute');
   if (null !== $customAttributeValue) {
   $myAttributeValue = $customAttributeValue->getValue();
   return  $myAttributeValue;
   }           
   }

}

2. Used above block function in template file like below

   echo $block->getCustomAttribute(2); //where 2 is category id

No comments:

Post a Comment