Get Product Collection Filter By Visibility in Magento 2

Create Products.php block

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;
    }
}

Insert in phtml file

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 Cache And Check Result

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.