Mình đã từng hướng dẫn các bạn sắp xếp danh sách sản phẩm theo giá và name. Trong bài viết này mình sẽ hướng dẫn các bạn custom sắp xếp sản phẩm theo lượt view trong Magento 2. Và việc bạn muốn sắp xếp danh sách sản phẩm theo bán chạy nhất thì cũng tương tự.
Trước tiên các bạn cần vào Stores > Settings > Configuration. Ở tab General các bạn chọn section Reports và ở field Enable Reports các bạn chọn Yes để kích hoạt tính năng thống kê.

Sắp xếp danh sách sản phẩm theo lượt view
ViMagento/HelloWorld/etc/frontend/di.xml
1 2 3 4 5 6 7 8 9 |
<?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\Config"> <plugin name="sortby_add_custom_option" type="ViMagento\HelloWorld\Plugin\Model\Config" /> </type> <type name="Magento\Catalog\Block\Product\ProductList\Toolbar"> <plugin name="sortby_extend_default_sort_filters" type="ViMagento\HelloWorld\Plugin\Block\Toolbar" /> </type> </config> |
ViMagento/HelloWorld/Plugin/Model/Config.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
<?php namespace ViMagento\HelloWorld\Plugin\Model; class Config { /** * Add custom Sort By option * * @param \Magento\Catalog\Model\Config $catalogConfig * @param array $options * @return array [] * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ public function afterGetAttributeUsedForSortByArray(\Magento\Catalog\Model\Config $catalogConfig, $options) { // new sorting option $customOption['most_viewed'] = __('Most Viewed'); // merge default sorting options with custom options $options = array_merge($customOption, $options); return $options; } } |
ViMagento/HelloWorld/Plugin/Block/Toolbar.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 |
<?php namespace ViMagento\HelloWorld\Plugin\Block; use Magento\Framework\App\ResourceConnection; use Magento\Framework\DB\Select; /** * Product list toolbar plugin */ class Toolbar { const SORT_ORDER_DESC = 'DESC'; /** * @var \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection */ protected $_collection = null; /** * DB connection * * @var \Magento\Framework\DB\Adapter\AdapterInterface */ protected $_conn; /** * @var boolean */ protected $_subQueryApplied = false; /** * Constructor * * @param \Magento\Framework\App\ResourceConnection $resource */ public function __construct(ResourceConnection $resource) { $this->_conn = $resource->getConnection('catalog'); } /** * Plugin - Used to modify default Sort By filters * * @param \Magento\Catalog\Block\Product\ProductList\Toolbar $subject * @param null $result * @param \Magento\Framework\Data\Collection $collection * @return Toolbar * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ public function afterSetCollection(\Magento\Catalog\Block\Product\ProductList\Toolbar $subject, $result, $collection ) { $this->_collection = $collection; if ($subject->getCurrentOrder() == 'most_viewed') { if (!$this->_subQueryApplied) { $reportEventTable = $this->_collection->getResource()->getTable('report_viewed_product_aggregated_monthly'); $subSelect = $this->_conn->select()->from( ['viewed_table' => $reportEventTable], 'views_num' )->where( 'viewed_table.product_id = e.entity_id' ); $this->_collection->getSelect()->reset(Select::ORDER)->columns( ['views_num' => $subSelect] )->order( 'views_num ' . self::SORT_ORDER_DESC ); $this->_subQueryApplied = true; } } return $this; } } |
Bạn có thể thấy trong cơ sở dữ liệu có các bảng thống kê lượt view theo ngày, theo tháng, theo năm. Tùy theo yêu cầu mà bạn có thể thay thế, ở đây tôi sẽ ví dụ là sắp xếp danh sách sản phẩm theo tháng nên tôi sẽ sử dụng bảng report_viewed_product_aggregated_monthly.

Nhưng điều các bạn cần lưu ý là bảng thống kê lượt view này của chúng ta đang là bảng trống. Chúng chẳng có dữ liệu nào cả. Mặc định chúng sẽ không tự động cập nhật. Các bạn phải làm mới chúng bằng cách vào Reports > Statistics > Refresh Statistics sau đó tích chọn vào Most Viewed và chọn Submit. Magento làm như vậy để tăng hiệu suất và trải nghiệm của người dùng.

Cuối cùng các bạn xóa cache bằng câu lệnh php bin/magento cache:clean để áp dụng những thay đổi bạn vừa thực hiện. Và trong bảng report_viewed_product_aggregated_monthly của tôi hiện giờ đang có 4 sản phẩm có lượt view lớn nhất, tôi sẽ kiểm tra trên trình duyệt.


Kết luận
Như bạn đã thấy ở trên 4 sản phẩm có lượt view nhiều nhất của tôi đã được sắp xếp đầu tiên. Và tôi cũng đã hoàn thành bài hướng dẫn sắp xếp danh sách sản phẩm theo lượt view trong Magento 2. Cám ơn các bạn đã đọc bài viết.