This is how to get product quantity in Magento product details 2 . Getting product id and SKU in Magento 2 brings you the exact Product ID number and SKU which are corresponding to the item you want to find. All you have to do is use the following commands in the admin console of your Magento 2 store. makes a great effort to write this topic, and we hope it will help you be clear about how to get the product ID and SKU in Magento 2.
Step 1: Declare the command to get product ID or SKU
app\code\Magepow\ProductQty\Block\ ProductQty.php
<?php
namespace Magepow\ProductQty\Block;
class ProductQty extends \Magento\Framework\View\Element\Template{
protected $_registry;
public function __construct(
\Magento\Framework\Registry $_registry
array $data
)
{
$this->_registry = $_registry;
parent::__construct($context, $data);
}
public function getCurrentProduct()
{
return $this->_registry->registry('current_product');
}
}
Step 2: Create a number processing function that prints the number of products
<?php
namespace Magepow\ProductQty\Block;
class ProductQty extends \Magento\Framework\View\Element\Template{
protected $_stockProduct;
protected $_registry;
public function __construct(
\Magento\CatalogInventory\Api\StockRegistryInterface $_stockProduct,
\Magento\Framework\View\Element\Template\Context $context,
\Magento\Framework\Registry $_registry
array $data
)
{
$this->_stockProduct = $_stockProduct;
$this->_registry = $_registry;
parent::__construct($context, $data);
}
public function getCurrentProduct()
{
return $this->_registry->registry('current_product');
}
public function getProductQty()
{
$product = $this->getCurrentProduct();
$productTypeInstance = $product->getTypeInstance();
if ($product->getTypeId() == \Magento\ConfigurableProduct\Model\Product\Type\Configurable::TYPE_CODE) {
$usedProducts = $productTypeInstance->getUsedProducts($product);
$count = 0;
foreach ($usedProducts as $child) {
$productQty = $this->_stockProduct->getStockItem($child->getId());
round($count+=$productQty->getData('qty'));
}
return $count;
} else {
$productQty = $this->_stockProduct->getStockItem($product->getId());
return round($productQty->getData('qty'));
}
}
}
Next, please use the below script to get the qty in the template file.
<?php
/**
* @var $block \Magepow\ProductQty\Block\ProductQty
*/
echo $block->getProductQty();
?>
Thank you for reading this article, please leave a comment below. Best regards