Magento – How to get custom category attribute value in front end in Magento 2

category-attributemagento2

I am using Magento 2.3

I have Created one custom attribute "Popular Category" for categories. Now I am trying to get the value of this attribute in front end but I am not getting it.

enter image description here

I have tried this using below code:

<?php
     $cid = 3131;
     $c = $objectManager->create('Magento\Catalog\Model\Category')->load($cid);
     echo $c->getResource()->getAttribute('popular_category')->getFrontend()->getValue($c); 
?>

But I am not getting any values at all.Please check my logic for custom attribute in below file.

app/code/Myvendor/CategoryAttributes/Setup/InstallData.php

<?php


namespace Rootways\CategoryAttributes\Setup;

use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Eav\Setup\EavSetup;
use Magento\Eav\Setup\EavSetupFactory;
use Magento\Catalog\Model\Category;
use Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface;

/**
 * @codeCoverageIgnore
 */
class InstallData implements InstallDataInterface
{
    /**
     * @var EavSetupFactory
     */
    private $eavSetupFactory;

    /**
     *
     * @param EavSetupFactory $eavSetupFactory
     */
    public function __construct(EavSetupFactory $eavSetupFactory)
    {
        $this->eavSetupFactory = $eavSetupFactory;
    }

    public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
    {
        /** @var EavSetup $eavSetup */
        $eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);
        $eavSetup->addAttribute(
            Category::ENTITY,
            'popular_category',
            [
                'type' => 'int',
                'label' => 'Popular Category',
                'input' => 'select',
                'required' => false,
                'sort_order' => 100,
                'global' => ScopedAttributeInterface::SCOPE_STORE,
                'group' => 'General Information',
                'visible_on_front' => true,
            ]
        );
    }
}
?>

I want to display images of those categories in which popular category is set to YES. So How can achieve this?

Best Answer

Using Custom Module (Recommended)

Create a simple module and add a helper class then call it in your phtml file. You can use Category's CollectionFactory class and select all attributes by using a star (*) symbol in addAttributeToSelect method. You can try this code example in your helper class.

protected $_categoryFactory;

public function __construct(
    // ...
    \Magento\Catalog\Model\ResourceModel\Category\CollectionFactory $collecionFactory,
    ) {
        // ...
        $this->_categoryFactory = $collecionFactory;
}

public function yourFunctionName()
{
    $catId = 5; // category id        
    $collection = $this->_categoryFactory
                    ->create()
                    ->addAttributeToSelect('*')
                    ->addAttributeToFilter('entity_id',['eq'=>$catId])
                    ->setPageSize(1);

    $catObj = $collection->getFirstItem();
    $catData = $catObj->getData(); // dump this line to check all data

    // ...
    return $catObj->getPopularCategory();
}

Call the helper method in your phtml file.

$helper = $this->helper('{Vendor}\{Module}\Helper\Data');
$values = $helper->yourFunctionName();

Using Object Manager (Not Recommended)

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$catId = 5; // category id 

$collection = $objectManager->create('Magento\Catalog\Model\ResourceModel\Category\CollectionFactory')
                ->create()
                ->addAttributeToSelect('*')
                ->addAttributeToFilter('entity_id',['eq'=>$catId])
                ->setPageSize(1);

$catObj = $collection->getFirstItem();
$catData = $catObj->getData(); // dump this line to check all data

echo $catObj->getPopularCategory();
Related Topic