3

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?

Yehuda Schwartz
  • 1,152
  • 3
  • 14
  • 33

4 Answers4

5

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;
}
Abdul
  • 9,701
  • 1
  • 20
  • 43
3

You can try this is code below:

$_product = $this->getProduct();
$sku = $_product->getSku(); 
LinoPham
  • 3,778
  • 5
  • 22
  • 45
0

This code is working for me in magento 2.

<?php
    if($_product) {
      $sku = $_product->getSku();
      echo $sku;
    }
?>
Wajahat Bashir
  • 402
  • 1
  • 3
  • 23
0

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.

Iveta Allogenes
  • 345
  • 2
  • 17