I have a site running Magento 2.2.1. I need to create a very simple PHP page that will look up a given product. I want to look up the product based on the SKU and just print the price and product URL out.
I have NO idea how to even start this. I have tried using this to test loading a product with ID = 1
//Get Object Manager Instance
$objectManager = MagentoFrameworkAppObjectManager::getInstance();
//Load product by product id
$product = $objectManager->create('MagentoCatalogModelProduct')->load(1);
but all that does is throw an exeception that ObjectManager is not found. So I tried including the /app/bootstrap.php
file beforehand, and that throws an error that the ObjectManager isn’t initialized.
Can anyone provide me with a simple example that I can drop into the root of my site that will allow me to look up a single product by sku? Or point me in the direction of some useful documentation?
2
Answers
You Cant just Load a Page By simple PHP file in magento Here is the procedure
1)create a layout file in you theme
2)register it inside layout.xml
3)add phtml to your layout file
4)add you code(in your question ) in that phtml file
the 2nd way is quite complecated
create module and in module controller render your code
The solution to load a product programmatically in simple PHP file by using
ObjectManager
, but this solution is not recommended by Magento 2.Recommended Solution (Magento 2)
In Magento 2, the recommended way of loading product is by using
ProductRepository
andProductFactory
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
SolutionIn Magento 2.1
ProductRepository
Solutionand, your
.phtml
file should look like this: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