Magento 2 – Get Attribute Set Name in Product Listing and Detail Page

attribute-setmagento2product

How can we retrieve the attribute set name for a product. I want to use it on product detail and listing page.

Best Answer

We can use \Magento\Eav\Api\AttributeSetRepositoryInterface to get attribute set name.

Detail Page

We need to override the \Magento\Catalog\Block\Product\View block. Inject this class on the constructor

/** @var \Magento\Eav\Api\AttributeSetRepositoryInterface $attributeSet **/
protected $attributeSet;

public function __construct(
    ......
    \Magento\Eav\Api\AttributeSetRepositoryInterface $attributeSet
    ......
) {
   ......
   $this->attributeSet = $attributeSet;
}


//Build method to get attribute set
public function getAttributeSetName() {

    $product = $this->getProduct();
    $attributeSetRepository = $this->attributeSet->get($product->getAttributeSetId());
    return $attributeSetRepository->getAttributeSetName();
}

Now, we can call in product detail page: $block->getAttributeSetName();

Listing page

We need to override \Magento\Catalog\Block\Product\ListProduct block

/** @var \Magento\Eav\Api\AttributeSetRepositoryInterface $attributeSet **/
protected $attributeSet;

public function __construct(
    ......
    \Magento\Eav\Api\AttributeSetRepositoryInterface $attributeSet
    ......
) {
   ......
   $this->attributeSet = $attributeSet;
}

public function getAttributeSetName($product) {

    $attributeSetRepository = $this->attributeSet->get($product->getAttributeSetId());
    return $attributeSetRepository->getAttributeSetName();
}

We can call $block->getAttributeSetName($_product).

Related Topic