In this article, I am going to explain how we can get the product collection or filter products based on custom attributes in Magento 2. In Magento product collection is one of the most important things because product collection is often required in different filters as well as requirements.
So there are multiple names of showing product collections on the frontends in Magento 2.
We can show the products collections on various conditions like on the load conditions on the get conditions on the filter conditions on the sort conditions but here I am going to explain based on filter product collections
- Filter product collection
- Load product collection
- Sort of product collection
- Get product collection
Load Filter Products Based on Attributes in Magento 2
In order to get the attribute filter product collections I Magento 2 we have to create the first block and then we can call that function in the template to load the product.
app/codeWishusucess/FilterProducts/registration.php
app/codeWishusucess/FilterProducts/etc/module.xml
app/codeWishusucess/FilterProducts/Block/Filterproducts.php
app/codeWishusucess/FilterProducts/Helper/Data.php
app/codeWishusucess/FilterProducts/view/frontend/templates/filterproducts.phtml
Register Filter Product Module
app/codeWishusucess/FilterProducts/registration.php
<?php /* * @Author Hemant Singh * @Developer Hemant Singh * @Module Wishusucess_FilterProducts * @copyright Copyright (c) Wishusucess (http://www.wishusucess.com/) */ \Magento\Framework\Component\ComponentRegistrar::register( \Magento\Framework\Component\ComponentRegistrar::MODULE, 'Wishusucess_FilterProducts', __DIR__ );
Give Basic Information of Module
app/codeWishusucess/FilterProducts/etc/module.xml
<?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/Module/etc/module.xsd"> <module name="Wishusucess_FilterProducts" setup_version="1.0.0" /> </config>
Create Block To Get Filter Products By Attribute
Here you have put the identifier of attributes in the addAttributeToFilter() function and set the visibility.
->addAttributeToSelect($this->catalogConfig->getProductAttributes()) //->addAttributeToFilter('entity_id', array('in'=>$producIds)) ->addAttributeToFilter('attribute_identifier', array('in'=>'1')) //Filter Product Attribute Collections ->setVisibility($this->productVisibility->getVisibleInCatalogIds());
Now you can get the attribute filter collections of the products.
app/codeWishusucess/FilterProducts/Block/Filterproducts.php
<?php namespace Wishusucess\FilterProducts\Block; use Magento\Catalog\Api\CategoryRepositoryInterface; use Magento\Catalog\Model\Category; use Magento\Catalog\Model\Product; use Magento\Eav\Model\Entity\Collection\AbstractCollection; use Magento\Framework\Exception\NoSuchEntityException; use Magento\Framework\DataObject\IdentityInterface; class Filterproducts extends \Magento\Catalog\Block\Product\AbstractProduct { /** * Default toolbar block name * * @var string */ protected $_defaultToolbarBlock = 'Magento\Catalog\Block\Product\ProductList\Toolbar'; /** * Product Collection * * @var AbstractCollection */ protected $_productCollection; /** * Catalog layer * * @var \Magento\Catalog\Model\Layer */ protected $_catalogLayer; /** * @var \Magento\Framework\Data\Helper\PostHelper */ protected $_postDataHelper; /** * @var \Magento\Framework\Url\Helper\Data */ protected $urlHelper; /** * @var CategoryRepositoryInterface */ protected $categoryRepository; protected $productCollectionFactory; protected $storeManager; protected $catalogConfig; protected $productVisibility; protected $scopeConfig; /** * @param Context $context * @param \Magento\Framework\Data\Helper\PostHelper $postDataHelper * @param \Magento\Catalog\Model\Layer\Resolver $layerResolver * @param CategoryRepositoryInterface $categoryRepository * @param \Magento\Framework\Url\Helper\Data $urlHelper * @param array $data */ public function __construct( \Magento\Catalog\Block\Product\Context $context, \Magento\Framework\Data\Helper\PostHelper $postDataHelper, \Magento\Catalog\Model\Layer\Resolver $layerResolver, CategoryRepositoryInterface $categoryRepository, \Magento\Framework\Url\Helper\Data $urlHelper, \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory, \Magento\Catalog\Model\Product\Visibility $productVisibility, array $data = [] ) { $this->_catalogLayer = $layerResolver->get(); $this->_postDataHelper = $postDataHelper; $this->categoryRepository = $categoryRepository; $this->urlHelper = $urlHelper; $this->productCollectionFactory = $productCollectionFactory; $this->storeManager = $context->getStoreManager(); $this->catalogConfig = $context->getCatalogConfig(); $this->productVisibility = $productVisibility; parent::__construct( $context, $data ); } public function getProducts() { $storeId = $this->storeManager->getStore()->getId(); $products = $this->productCollectionFactory->create()->setStoreId($storeId); $todayDate= date('Y-m-d', time()); $products ->addAttributeToSelect($this->catalogConfig->getProductAttributes()) ->addMinimalPrice() ->addFinalPrice() ->addTaxPercents() ->addUrlRewrite() ->setVisibility($this->productVisibility->getVisibleInCatalogIds()) ->addAttributeToFilter('news_from_date', array('date'=>true, 'to'=> $todayDate)) ->addAttributeToFilter('news_to_date', array('date'=>true, 'from'=> $todayDate)) ->addAttributeToSort('news_from_date','desc'); $products->setPageSize($this->getConfig('qty'))->setCurPage(1); $this->_eventManager->dispatch( 'catalog_block_product_list_collection', ['collection' => $products] ); return $products; } public function getLimitdeditions() { $storeId = $this->storeManager->getStore()->getId(); $products = $this->productCollectionFactory->create()->setStoreId($storeId); $products ->addAttributeToSelect($this->catalogConfig->getProductAttributes()) //->addAttributeToFilter('entity_id', array('in'=>$producIds)) ->addAttributeToFilter('limited_editions', array('in'=>'1'))// Filter Products Collection Based on Limited Editions Attribute ->addMinimalPrice() ->addFinalPrice() ->addTaxPercents() ->addUrlRewrite() ->setVisibility($this->productVisibility->getVisibleInCatalogIds()); $products->setPageSize($this->getConfig('qty'))->setCurPage(1); $this->_eventManager->dispatch( 'catalog_block_product_list_collection', ['collection' => $products] ); return $products; } public function getHighcomplication() { $storeId = $this->storeManager->getStore()->getId(); $products = $this->productCollectionFactory->create()->setStoreId($storeId); $products ->addAttributeToSelect($this->catalogConfig->getProductAttributes()) //->addAttributeToFilter('entity_id', array('in'=>$producIds)) ->addAttributeToFilter('high_complications', array('in'=>'1')) //Filter Product Collections Based on High Complication Attributes ->addMinimalPrice() ->addFinalPrice() ->addTaxPercents() ->addUrlRewrite() ->setVisibility($this->productVisibility->getVisibleInCatalogIds()); $products->setPageSize($this->getConfig('qty'))->setCurPage(1); $this->_eventManager->dispatch( 'catalog_block_product_list_collection', ['collection' => $products] ); return $products; } public function getSpecialeditions() { $storeId = $this->storeManager->getStore()->getId(); $products = $this->productCollectionFactory->create()->setStoreId($storeId); $products ->addAttributeToSelect($this->catalogConfig->getProductAttributes()) //->addAttributeToFilter('entity_id', array('in'=>$producIds)) ->addAttributeToFilter('special_editions', array('in'=>'1')) //Filter Products Based on Special Editions Attribute ->addMinimalPrice() ->addFinalPrice() ->addTaxPercents() ->addUrlRewrite() ->setVisibility($this->productVisibility->getVisibleInCatalogIds()); $products->setPageSize($this->getConfig('qty'))->setCurPage(1); $this->_eventManager->dispatch( 'catalog_block_product_list_collection', ['collection' => $products] ); return $products; } public function getComplication() { $storeId = $this->storeManager->getStore()->getId(); $products = $this->productCollectionFactory->create()->setStoreId($storeId); $products ->addAttributeToSelect($this->catalogConfig->getProductAttributes()) //->addAttributeToFilter('entity_id', array('in'=>$producIds)) ->addAttributeToFilter('complications', array('in'=>'1')) //Filter Products Based on Complication Attribute ->addMinimalPrice() ->addFinalPrice() ->addTaxPercents() ->addUrlRewrite() ->setVisibility($this->productVisibility->getVisibleInCatalogIds()); $products->setPageSize($this->getConfig('qty'))->setCurPage(1); $this->_eventManager->dispatch( 'catalog_block_product_list_collection', ['collection' => $products] ); return $products; } public function getBestseller() { $storeId = $this->storeManager->getStore()->getId(); $products = $this->productCollectionFactory->create()->setStoreId($storeId); $products ->addAttributeToSelect($this->catalogConfig->getProductAttributes()) //->addAttributeToFilter('entity_id', array('in'=>$producIds)) ->addAttributeToFilter('bestseller', array('in'=>'1')) //Filter Product Best Seller Product Collection ->addMinimalPrice() ->addFinalPrice() ->addTaxPercents() ->addUrlRewrite() ->setVisibility($this->productVisibility->getVisibleInCatalogIds()); $products->setPageSize($this->getConfig('qty'))->setCurPage(1); $this->_eventManager->dispatch( 'catalog_block_product_list_collection', ['collection' => $products] ); return $products; } }
Create Helper Class For Filter Products
app/codeWishusucess/FilterProducts/Helper/Data.php
<?php /* * @Author Hemant Singh * @Developer Hemant Singh * @Module Wishusucess_FilterProducts * @copyright Copyright (c) Wishusucess (http://www.wishusucess.com/) */ namespace Wishusucess\FilterProducts\Helper; class Data extends \Magento\Framework\App\Helper\AbstractHelper { public function __construct( \Magento\Framework\App\Helper\Context $context ) { parent::__construct($context); } public function getConfigData($path) { $value = $this->scopeConfig->getValue($path, \Magento\Store\Model\ScopeInterface::SCOPE_STORE); return $value; } }
Print Attribute Filter Collections Data in Phtml
app/codeWishusucess/FilterProducts/view/frontend/templates/filterproducts.phtml
<?php $_productCollection = $this->getProducts(); $_helper = $this->helper('Magento\Catalog\Helper\Output'); ?>
We can use this code to get the product collection in the vew/frontend/templates/filterproducts.phtml files.
Hire Magento 2 Expert Developer to Develop Your Store
Related Post:
Override Checkout Street Address Placeholder in Magento 2
Search AutoComplete: Magento 2 Module Add All Category for Search
Sort By Price: Add Sort By Price High to Low & Low To High in Magento 2
Recommended Post:
Magento 2.4 Installation Guide: How to Install Magento 2.4.2
Magento Store: Best 36 Magento Websites Example in The World
SEO Packages: How Much Do SEO Packages Cost in India, SEO Pricing