i am adding a phtml with after_body_start reference
how do I display the SKU of a product if the phtml is being added to a product page?
i am adding a phtml with after_body_start reference
how do I display the SKU of a product if the phtml is being added to a product page?
There may be a more efficient way depending on how you added this phtml, but if it only shows on a product page, try getting the product like this:
$current_product = Mage::registry('current_product');
if($current_product) {
$sku = $current_product->getSku();
// output sku
echo $sku;
}
You can try this is code below:
$_product = $this->getProduct();
$sku = $_product->getSku();
Mage_Catalog_Block_Product_View
– LinoPham
Nov 18 '15 at 17:56
This code is working for me in magento 2.
<?php
if($_product) {
$sku = $_product->getSku();
echo $sku;
}
?>
To get product sku in Magento (Adobe Commerce) 2.x.x in your custom phtml template file you need to add the appropriate block class in your layout file, for example:
in catalog_product_view.xml :
<referenceBlock name="product.info.addtocart">
<block class="Magento\Catalog\Block\Product\View" name="my-block" template="Vendor_Module::custom.phtml" />
</block>
</referenceBlock>
in your custom.phtml :
<?php
declare(strict_types=1);
/** @var Escaper $escaper /
/* @var $block \Magento\Catalog\Block\Product\View */
$_product = $block->getProduct();
$sku = $_product->getSku();
?>
<div>
Product sku:
<span><?= $escaper->escapeHtml($sku) ?></span>
</div>
You can use methods from different blocks, by declaring the block class on your block tag in xml layout, then call the methods in your custom phtml file.
`
getData($att); ?>"]);` – Yehuda Schwartz Nov 19 '15 at 14:23