How can I call a widget that displays product from a specific category in a phtml file?
Currently I can only display "all_products" in my phtml file like that:
echo $this->getLayout()->createBlock("Magento\Catalog\Block\Product\Widget\NewWidget")->setDisplayType("all_products")->setProductsCount("5")->setTemplate("product/widget/new/content/new_grid.phtml")->toHtml();
How to do this with products from specific category and not all products?
Best Answer
There is a widget for arbitrary product lists (as mentioned by @Nits). If you insert the widget on any CMS page or block and turn off the WYSIWYG editor ("Hide editor" button), you can see how the parameters look like.
For example, I created the widget with the condition "category = 4", showing five products:
From that you can see that the class is
Magento\CatalogWidget\Block\Product\ProductsList
and you can create it programmatically as follows:But "conditions_encoded" is a serialized array (with some characters replaced for WYSIWYG compatibility). This serialized array is difficult to construct manually, but luckily you can also use "conditions" with the unserialized value instead in PHP code. So you can replace the last line from above with:
Then output: