To display the product count for each autosuggestion keyword in Magento, you will need to perform the following steps:
Override the Magento\CatalogSearch\Model\Autocomplete\DataProvider class in your custom module.
In your overridden class, modify the getItems() method to retrieve the search suggestion data along with the product count for each keyword. You can achieve this by creating a custom query using the Magento\Catalog\Model\ResourceModel\Product\Collection and Magento\Catalog\Model\ResourceModel\Product\CollectionFactory classes.
Here's an example implementation for the getItems() method:
public function getItems()
{
$output = [];
// Retrieve the search suggestion data
$suggestions = parent::getItems();
// Create a product collection factory
$productCollectionFactory = $this->_objectManager->get(\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory::class);
foreach ($suggestions as $suggestion) {
// Create a product collection
$productCollection = $productCollectionFactory->create();
// Apply the search filters to the product collection
$query = $this->_queryFactory->get();
$queryText = $query->getQueryText();
$searchCriteriaBuilder = $this->_searchCriteriaBuilderFactory->create();
$searchCriteria = $searchCriteriaBuilder
->addFilter('name', '%' . $queryText . '%', 'like')
->addFilter('visibility', \Magento\Catalog\Model\Product\Visibility::VISIBILITY_BOTH, 'in')
->addFilter('status', \Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED, 'in')
->create();
$productCollection->addAttributeToSelect('*');
$productCollection->addFieldsToFilter($searchCriteria);
// Get the product count for the current keyword
$productCount = $productCollection->getSize();
// Add the product count to the suggestion data
$output[] = [
'title' => $suggestion['title'],
'num_results' => $productCount,
'url' => $suggestion['url'],
];
}
return $output;
}
In this example, we first retrieve the search suggestion data using the parent getItems() method. Then, we create a Magento\Catalog\Model\ResourceModel\Product\Collection object and apply the search filters to it. After that, we get the size of the collection to get the product count for the current keyword. Finally, we add the product count to the suggestion data and return it.
Note: You may need to modify the search filters based on your specific requirements.
- After implementing the above code, the product count should now be available in the autosuggestion dropdown. You can modify the autocomplete.phtml template file to display the product count alongside the suggestion keyword.
That's it! You should now have the product count available for each autosuggestion keyword in Magento.