Question:

Get stock for a product in Magento 2

Aria: 20 May 2022

I want to display the current stock of a specific product in a theme. How can I do that?

getStock() does not seem to work.

Answer:
Raelynn: 20 May 2022

It mainly depends on the file where you want to display it.

First you need to find out the block where you want to display that info.

Then you'll have to setup a preference for that block in a custom module:

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <preference for="Path\To\Core\Block\You\Want\To\Rewrite" type="Vendor\Module\Block\Custom" />
</config>

Then create your Block\Custom file:

<?php

namespace Vendor\Module\Block;

class Custom extends Path\To\Core\Block\You\Want\To\Rewrite
{
    protected $_stockRegistry;

    public function _construct(
         ...
         \Magento\CatalogInventory\Api\StockRegistryInterface $stockRegistry,
         ...)
     {
         $this->_stockRegistry = $stockRegistry;
         ...
     }

     public function getStockItem($productId)
     {
         return $this->_stockRegistry->getStockItem($productId);
     }
}

Please note the ... in the constructor. You'll have to replace those with the original arguments from the block you're rewriting and then call the parent constructor with the original parameters.

Finally in your template you can do:

$stockItem = $block->getStockItem($productId);
$stockQty = $stockItem->getQty();