Get Product Collection Filter By Visibility in Magento 2

As you might already know, product collection plays a paramount role in every project of Magento 2 developer. In the previous post, I have shown you the steps to get product collection by category, therefore, in today article, I will guide you how to get product collection filter by visibility in Magento 2.

How to get product collection filter by visibility

Step 1: Create Products.php block

To get a product collection filter by visibility, firstly, you need to create a Products.php block. In order to create it, follow this path Mageplaza/HelloWorld/Block/Products.php

<?php
namespace Mageplaza\HelloWorld\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;
    }
}

Step 2: Insert in phtml file

After you have already had a collection in your block, now follow the below snippet to get the Product collection from the block: Mageplaza/HelloWorld/view/frontend/templates/product-list.phtml

$collection = $block->getProductCollection;
foreach ($collectionas $_product) {
    echo $_product->getName() . ' - ' . $_product->getProductUrl() . '<br />';
}

Step 3: Flush Cache & Test result

Finally, to finish getting the product collection filter by visibility, let’s flush cache and test the result.

Conclusion

Above are three steps which could help you in getting product collection filter by visibility. I hope it will become helpful for you when managing product collection.

Enjoyed the tutorial? Spread it to your friends!