You can get list of all attribute options value by Category attribute code in Magento 2. You can fetch all the list of available options for the dropdown, multi select, checkbox type.
Let’s take an Example, We can get all the CMS Static Block assigned to specific attribute called, Add CMS Block(landing_page) is the drop down type category attribute.
You can get all the options label, value pair for the attribute from the interface class, Magento\Catalog\Api\CategoryAttributeOptionManagementInterface.
<?php namespace Jesadiya\Category\Model; use Exception; use Magento\Eav\Api\Data\AttributeOptionInterface; use Magento\Catalog\Api\CategoryAttributeOptionManagementInterface; class CategoryAttributeOptions { /** * @var CategoryAttributeOptionManagementInterface */ private $categoryAttribute; public function __construct( CategoryAttributeOptionManagementInterface $categoryAttribute ) { $this->categoryAttribute = $categoryAttribute; } /** * list of options value-label pair attribute * * @return AttributeOptionInterface[] */ public function getCategoryAttributeOption($categoryAttributeCode) { $categoryAttributeData = []; try { $categoryAttributeData = $this->categoryAttribute->getItems($categoryAttributeCode); } catch (Exception $exception) { throw new Exception($exception->getMessage()); } return $categoryAttributeData; } }
Call from the template or PHP class to retrieve list of options,
You have to pass Category attribute code to retrieve list of options for specific attribute, In Our Case, It wil be landing_page category attirbute,
$categoryAttributeCode = "landing_page"; $options = $this->getCategoryAttributeOption($categoryAttributeCode); foreach ($options as $categoryOptionValue){ print_r($categoryOptionValue->debug()); }
Output:
AttributeOptionInterface[]
Array ( [value] => ) Array ( [value] => 1 [label] => Catalog Events Lister ) Array ( [value] => 2 [label] => Footer Links Block ) Array ( [value] => 3 [label] => Contact us info ) Array ( [value] => 4 [label] => Sale Left Menu Block ) Array ( [value] => 5 [label] => Gear Left Menu Block ) ... ...