CommercePeer Brand Logo


Programmatically: Magento 2 Product Entity

Programmatically: How to create custom Magento product filters

Step 1: Create a new module

Create a new folder for your module in the app/code directory. For example, let's name it MyCompany_MyModule.

Inside the MyCompany_MyModule folder, create the following files: etc/module.xml: This file defines the module and its dependencies. etc/frontend/layout.xml: This file defines the layout for your frontend. Model/Product/Filter/MyFilter.php: This file will contain the logic for your custom filter.

Step 2: Define the module and its dependencies

In etc/module.xml, add the following code:


	
	
    
        
            Magento_Catalog
        
    
	
	

Step 3: Define the layout

In etc/frontend/layout.xml, add the following code:


	
	
    
        
            
        
    
	
	

Step 4: Create the filter class

In Model/Product/Filter/MyFilter.php, add the following code:


	namespace MyCompany\MyModule\Model\Product\Filter;

	class MyFilter extends \Magento\Catalog\Block\Product\ListProduct\AbstractListProduct
{
    protected $_filter;

    public function __construct(
        \Magento\Framework\App\RequestInterface $request,
        \Magento\Framework\Data\CollectionFactory $collectionFactory,
        \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,
        array $data = []
    ) {
        parent::__construct($request, $collectionFactory, $productCollectionFactory, $data);
        $this->_filter = new \MyCompany\MyModule\Model\Product\Filter\MyFilterData();
    }

    public function getFilters()
    {
        return $this->_filter->getFilters();
    }
}
	

Step 5: Create the filter data class

In Model/Product/Filter/MyFilterData.php, add the following code:


	namespace MyCompany\MyModule\Model\Product\Filter;

	class MyFilterData
{
    public function getFilters()
    {
        $filters = [];
        // Add your filter options here
        $filters[] = ['label' => 'Color', 'values' => ['red', 'blue', 'green']];
        return $filters;
    }
}
	

Step 6: Create the template

Create a new file myfilter.phtml in the view/frontend/web directory of your module:


	$filters = $block->getFilters();
	

Step 7: Run the setup script

Run the following command to deploy and enable your module:


	php bin/magento setup:deploy
	php bin/magento module:enable MyCompany_MyModule
	

LET’S WORK TOGETHER

We love working with Small Businesses, Retailers, Manufacturers. Our team is here to Help.

→ Schedule Free Consultant Now
Copyright © 2024 CommercePeer. All Rights Reserved.