Displaying Best Selling Items by Category in Magento
As a senior developer specializing in e-commerce platforms like Magento, I often receive queries about customizing built-in functionalities to meet specific business needs. One common request is to display best selling items within particular product categories.
Let’s break down your question and provide an accurate solution using native Magento features and some custom code enhancements.
Understanding the Default Magento Best Seller Functionality
Magento 2 comes with a built-in feature to showcase top selling products on the homepage. The collection used for this can be found in vendor/magento/module-catalog/Model/ResourceModel/Product/Collection.php. However, by default, it doesn’t consider product categories.
Editing for Category-Specific Best Sellers
To achieve your requirement, you’ll need to create a new collection and modify the sales aggregation to filter by category. Here’s a step-by-step guide:
- Create a New Product Collection
In app/code/Vendor/Module/etc/config.xml, add the following configuration to create a new product collection model:
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App etc/config.xsd">
<type name="Magento\Catalog\Model\ResourceModel\Product\CollectionFactory">
<arguments>
<argument name="collections" xsi:type="array">
<item name="top_sellers_by_category" xsi:type="string">Vendor\Module\Model\ResourceModel\Product\Collection</item>
</argument>
</arguments>
</type>
</config>
- Implement the Custom Collection
In app/code/Vendor/Module/Model/ResourceModel/Product/Collection.php, extend the default collection and filter by category:
use Magento\Framework\App\RequestInterface;
class Collection extends \Magento\Catalog\Model\ResourceModel\Product\Collection
{
protected $_request;
public function __construct(
\Magento\Framework\Data\Collection\EntityFactoryInterface $entityFactory,
\Psr\Log\LoggerInterface $logger,
\Magento\Framework\Data\Collection\Db\FetchStrategyInterface $fetchStrategy,
\Magento\Framework\Event\ManagerInterface $eventManager,
\Magento\Framework\Stdlib\DateTime\DateTime $date,
\Magento\Eav\Model\Config $eavConfig,
RequestInterface $request
) {
$this->_request = $request;
parent::__construct($entityFactory, $logger, $fetchStrategy, $eventManager, $date, $eavConfig);
}
protected function _prepareSelect()
{
parent::_prepareSelect();
if ($categoryId = $this->_request->getParam('cat')) {
$this->_joinCategory($categoryId);
}
return $this;
}
private function _joinCategory($categoryId)
{
$this->getSelect()->join(
['category_product' => $this->getTable('catalog_category_product')],
'e.entity_id = category_product.product_id'
. ' AND category_product.category_id=' . (int)$categoryId,
[]
);
}
}
- Using the New Collection
In your layout XML file, you can now use this collection in a block:
<block class="Magento\Catalog\Block\Product\NewProducts" name="top_sellers_by_category" template="catalog/product/new.phtml">
<arguments>
<argument name="products_count" xsi:type="number">8</argument>
<argument name="category_id" xsi:type="string">24</argument> <!-- Change this to your category ID -->
</arguments>
<action method="setCollection">
<argument name="collection" xsi:type="object">Magento\Catalog\Model\ResourceModel\Product\CollectionFactory::get('top_sellers_by_category')</argument>
</action>
</block>
Conclusion
Displaying best selling items within a specific category in Magento requires extending the default product collection and filtering by category. By following this guide, you can create a new block that showcases top products for any desired category.
Remember to replace Vendor with your actual vendor name and update the category ID (24) to match your store’s configuration. Make sure to clear the cache after implementing these changes.
For more advanced customizations or if you’re looking to outsource Magento development, feel free to reach out to Laravel Company (https://laravelcompany.com/magento-development). Our experienced team can help optimize your e-commerce performance and deliver tailored solutions.
Happy coding!