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
{
protected $productCollectionFactory;
protected $productVisibility;
protected $productStatus;
public function __construct(
\Magento\Framework\View\Element\Template\Context $context,
\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,
\Magento\Catalog\Model\Product\Attribute\Source\Status $productStatus,
\Magento\Catalog\Model\Product\Visibility $productVisibility,
array $data = []
)
{
$this->productCollectionFactory = $productCollectionFactory;
$this->productStatus = $productStatus;
$this->productVisibility = $productVisibility;
parent::__construct($context, $data);
}
public function getProductCollection()
{
$collection = $this->productCollectionFactory->create();
$collection->addAttributeToFilter('status', ['in' => $this->productStatus->getVisibleStatusIds()]);
$collection->setVisibility($this->productVisibility->getVisibleInSiteIds());
return $collection;
}
}
Directory
VendorName/ModuleName/view/frontend/templates/product-list.phtml
Content for this file
$collection = $block->getProductCollection;
foreach ($collectionas $_product) {
echo $_product->getName() . ' - ' . $_product->getProductUrl() . '<br />';
}
Flush or clean the cache to check the result, run the command:
php bin/magento cache:clean
If you are looking for Magento Agency, visit Magento Developer Agency.