The solution to load a product programmatically in simple PHP file by using ObjectManager
, but this solution is not recommended by Magento 2.
<?php
include('app/bootstrap.php');
use Magento\Framework\App\Bootstrap;
$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
$state = $objectManager->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');
$productId = 1;
$product = $objectManager->create('Magento\Catalog\Model\Product')->load($productId);
echo $product->getName();
?>
Recommended Solution (Magento 2)
In Magento 2, the recommended way of loading product is by using ProductRepository
and ProductFactory
in a proper custom module instead of simple PHP file. Well, by using below (recommended) code, you can load product in your custom block.
ProductFactory
Solution
<?php
namespace [Vendor_Name]\[Module_Name]\Block;
use Magento\Catalog\Model\ProductFactory;
class Product extends \Magento\Framework\View\Element\Template
{
protected $_productloader;
public function __construct(
ProductFactory $_productloader
) {
$this->_productloader = $_productloader;
}
public function getLoadProduct($id)
{
return $this->_productloader->create()->load($id);
}
}
In Magento 2.1
ProductRepository
Solution
namespace [Vendor_Name]\[Module_Name]\Block;
use Magento\Catalog\Api\ProductRepositoryInterface;
class Product extends \Magento\Framework\View\Element\Template
{
protected $_productRepository;
public function __construct(
ProductRepositoryInterface $productRepository
) {
$this->_productRepository = $productRepository;
}
public function getProduct($id)
{
return $product = $this->productRepository->getById($id);
}
}
and, your .phtml
file should look like this:
$productId = 1;
$product = $this->getLoadProduct($productId);
echo $product->getName();
I hope, you already know how to create a custom module in Magento 2 or if you want then just read this blog post How to create a basic module in Magento 2