This article shows how to load product by it’s ID and then get all attributes associated with that product in Magento 2. We print the attribute code, attribute name, and attribute value of all the attributes related to any particular product.
We will be using Magento 2’s Service Layer for this task. Use of Service Layer is highly encouraged by Magento.
Below is a block class of my custom module (Chapagain_HelloWorld). I have injected object of \Magento\Catalog\Model\ProductRepository class in the constructor of my module’s block class.
app/code/Chapagain/HelloWorld/Block/HelloWorld.php
<?php
namespace Chapagain\HelloWorld\Block;
class HelloWorld extends \Magento\Framework\View\Element\Template
{
protected $_productRepository;
public function __construct(
\Magento\Backend\Block\Template\Context $context,
\Magento\Catalog\Model\ProductRepository $productRepository,
array $data = []
)
{
$this->_productRepository = $productRepository;
parent::__construct($context, $data);
}
public function getProductById($id)
{
return $this->_productRepository->getById($id);
}
public function getProductBySku($sku)
{
return $this->_productRepository->get($sku);
}
}
?>
Now, we load the product by id and get all attribute code, attribute name, and attribute value for the product in template file.
$id = YOUR_PRODUCT_ID;
$_product = $block->getProductById($id);
$attributes = $product->getAttributes();
foreach ($attributes as $attribute) {
echo $attribute->getAttributeCode(); echo '<br />';
echo $attribute->getStoreLabel(); echo '<br />';
echo $attribute->getFrontendLabel(); echo '<br />';
echo $attribute->getFrontend()->getLabel(); echo '<br />';
// you might not get value for all attributes
echo $attribute->getFrontend()->getValue($product); echo '<br />';
}
Hope this helps. Thanks.