Hi i want to show the products attribute code and it's value using the product id.
How can i do this? Any help would be appreciated.
Magento Stack Exchange is a question and answer site for users of the Magento e-Commerce platform. It only takes a minute to sign up.
Sign up to join this communityHi i want to show the products attribute code and it's value using the product id.
How can i do this? Any help would be appreciated.
You can use this,
namespace NameSpace\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);
}
}
and in your phtml.
$id = YOUR_PRODUCT_ID;
$product = $block->getProductById($id); // load product bi 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 />';
}
All other answer are helpful but i want to get the attribute value with multi select also. so i used the
$product->getResource()->getAttribute($code)->getFrontend()->getValue($product);
May it help to some one, Thanks.
it depends on the attribute type.
//to get all the attributes of the product by id
$id = 1; //your Product id
$data = $this->_objectManager->create('Magento\Catalog\Model\Product')->load($id)->getData();
var_dump($data);
// also you can get the attribute value dpendong on the attribute type
//for example you have text field Attribute called(test) to get it's value
echo $this->_objectManager->create('Magento\Catalog\Model\Product')->load($id)->getTest();
//to get a value of select/multi-select Attribute called(test) will return as array
var_dump($this->_objectManager->create('Magento\Catalog\Model\Product')->load($id)->getAttributeText('test'));