I have a custom phtml file which I am calling on a page, and I would like to display the products from the site in this block. I'm doing a migration from m1 and in the original file the following code was used:
$products = Mage::getModel('catalog/category')->load(4)
->getProductCollection()
->addAttributeToSelect('*')
->addAttributeToFilter('status', 1)
->addAttributeToFilter('visibility', 4);
I have seen using a block is the best way to go, avoiding object manager, such as the following:
use Magento\Catalog\Model\ProductFactory;
use Magento\Framework\View\Element\Template\Context;
protected $_productFactory;
public function __construct(
Context $context,
ProductFactory $productFactory,
array $data = array()
) {
$this->_productFactory = $productFactory;
parent::__construct($context, $data);
}
public function getProductCollection() {
$productCollection = $this->_productFactory->create()->getCollection();
return $productCollection;
}
However I don't know how to add a block to a theme, only an extension/module.
Can you add a block to a theme or do I need to make an extension just to allow products? If it is possible how does the structure for the theme then work?
Update:
(Note just using Vendor as an example) I created a new extension in:
app/code/Vendor/ProductDisplay
I created a new class of ProductDisplay in
app/code/Vendor/ProductDisplay/ProductDisplay.php
I created a new templated in
app/code/Vendor/ProductDisplay/view/frontend/templates/productdisplay.phtml
I'm calling it in my cms page with:
{{block class="Vendor\Productdisplay\Block\ProductDisplay" template="Vendor_ProductDisplay::productdisplay.phtml"}}