15/08/2022
We use cookies to make your experience better. To comply with the new e-Privacy directive, we need to ask for your consent to set the cookies. Learn more.
We use cookies to make your experience better. To comply with the new e-Privacy directive, we need to ask for your consent to set the cookies. Learn more.
Directory
VendorName/ModuleName/Block/Products.php
Content for this file
<?php
namespace VendorName\ModuleName\Block;
class Products extends \Magento\Framework\View\Element\Template
{
/**
* @var \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory
*/
protected $_productCollectionFactory;
public function __construct(
\Magento\Backend\Block\Template\Context $context,
\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory
)
{
$this->_productCollectionFactory = $productCollectionFactory;
parent::__construct($context);
}
public function getProductCollectionByCategories($ids)
{
$collection = $this->_productCollectionFactory->create();
$collection->addAttributeToSelect('*');
$collection->addCategoriesFilter(['in' => ids]);
return $collection;
}
}
Directory
VendorName/ModuleName/view/frontend/templates/list.phtml
Content for this file
$ids = [1,2,3];
$categoryProducts = $block->getProductCollectionByCategories($ids);
foreach ($categoryProducts as $product) {
echo $product->getName() . ' - ' . $product->getProductUrl() . '<br />';
}
Now flush or clear the cache to check the result, the command:
php bin/magento cache:clear
If you are looking for Magento Developers, visit Magento Web Agency.