When a user is making a search on my website I would like to search into categories name, for example if the user is searching for "house" I would like to display all products containing "house" in their name (default behavior) but also all products of categories containing "house" in their name.

I wrote the code below, it's working great I have all products but the toolbar is not working anymore (order, limit, pager...).Is there any way to "reload" the toolbar with my new collection?

Thanks !

File: di.xml

<!-- Set plugin -->
<type name="Magento\Catalog\Model\Layer\Search\CollectionFilter">
    <plugin name="CategoryName_Search" type="My\Module\Model\Layer\Search\Plugin\CollectionFilter" />

File: My\Module\Model\Layer\Search\Plugin\CollectionFilter

public function afterFilter(
\Magento\Catalog\Model\Layer\Search\CollectionFilter $subject,
Category $category
) {
$query = $this->queryFactory->get();

if (!$query->isQueryTextShort()) {
    //Get categories list by name
    $categoryCollection = $this->collectionFactory
      ->addAttributeToFilter('name', array('like' => '%'.$query->getQueryText().'%'));

    //For each product in these categories add product to search collection
    foreach($categoryCollection as $category) {
      $categoryProducts = $category->getProductCollection()->addAttributeToSelect('*');

      foreach($categoryProducts as $product) {
        if (!$collection->getItemById($product->getId())) {
  • does anyone have an idea how to fix this ? Thanks a lot ! – magentodev Mar 22 at 12:59
  • did you find any solution for that ? – Camit1dk Oct 24 at 7:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.