Add custom column or attribute filter in product collection
Hello Friends!!!
In this blog, we will learn how we can add a custom attribute or custom column filter to the product collection.
Here, we will create an around plugin for the addAttributeToSelect method of Magento\Catalog\Model\ResourceModel\Product\Collection class.
In this plugin, we will add a filter of the custom column or custom attribute to the product collection. To proceed with this, please follow the below steps:
Step1. Create di.xml file inside the app/code/Vendor/Module/etc/ directory.
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<type name="Magento\Catalog\Model\ResourceModel\Product\Collection">
<plugin name="Vendor_Module::aroundProductCollection" type="Vendor\Module\Plugin\Product" sortOrder="1"/>
</type>
</config>
Step2. Create Product.php file inside the app/code/Vendor/Module/Plugin/ directory.
<?php
namespace Vendor\Module\Plugin;
class Product
{
/**
* @var Magento\Framework\App\State
*/
protected $appState;
/**
* Initialize dependencies
*
* @param \Magento\Framework\App\State $appState
*/
public function __construct(
\Magento\Framework\App\State $appState
) {
$this->appState = $appState;
}
/**
* Around plugin of addAttributeToSelect function
*
* @param \Magento\Catalog\Model\ResourceModel\Product\Collection $subject
* @param \Closure $proceed
* @param string $attribute
* @param boolean $joinType
* @return void
*/
public function aroundAddAttributeToSelect(
\Magento\Catalog\Model\ResourceModel\Product\Collection $subject,
\Closure $proceed,
$attribute,
$joinType = false
) {
$appState = $this->appState;
$skutoHideProduct = "test";
$result = $proceed($attribute, $joinType = false);
$code = \Magento\Backend\App\Area\FrontNameResolver::AREA_CODE;
if ($appState->getAreaCode() == $code) {
//add filter to hide test sku's product at frontend and admin's product grid collection
$result->addFieldToFilter('sku', ['neq' => $skutoHideProduct]);
}
//add custom column/attribute filter in collection
$result->addFieldToFilter('custom_column', ['eq' => 'value']);
return $result;
}
}
Now, see the result at the frontend and admin end in product grid collection.
Hope this will be helpful.
Thanks 🙂
Categories:
Magento 2
Tags:
add custom attribute filter to product collection add custom column filter to product collection Add custom column or attribute filter in product collection custom column filter in product collection for frontend custom filter in product grid collection filter in product collection hide specific product at frontend and admin product grid collection hide specific product in product grid collection at admin end product grid collection filter with area
View Comments
Comment or Ask a Question
Quick Links