It’s never ‘job done’ when it comes to providing exceptional customer experiences. It is necessary to offer out-of-the-box functionalities to customers for their convenience.
Bringing products with certain criteria to the top of the page can be particularly useful for customers who aren’t exactly sure what they want.
Default Magento 2 provides three options for product sorting on category page.
- Product
- Position
- Name
To increase and maintain user efficiency, default sorting options are not enough. We have to make a remarkable effort to present more sorting facilities for customers. You can refer Magento 2 Improved Sorting extension to sort products by options such as best sellers, ratings, top-rated, most reviewed, etc.
Mostly customers are curious by nature and always affectionate towards browsing the latest products. Today, I’ve come up with the solution to add sort by newest product option in Magento 2.
Steps to Add Sort by Newest Product Option in Magento 2
1 . Create di.xml file in Vendor/Module/etc
1 2 3 4 5 6 7 8 9 10 | <?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="Vendor_ModuleName::addCustomOptions" type="Vendor\Module\Plugin\Model\Config"/> </type> <type name="Magento\Catalog\Block\Product\ProductList\Toolbar"> <plugin name="catalog_productlist_toolbar_plugin" type="Vendor\Module\Plugin\Product\ProductList\Toolbar"/> </type> </config> |
2 . Create Config.php file in Vendor/Modulename/Plugin/Model
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | <?php namespace Vendor\Modulename\Plugin\Model; use Magento\Store\Model\StoreManagerInterface; class Config { protected $_storeManager; public function __construct( StoreManagerInterface $storeManager ) { $this->_storeManager = $storeManager; } public function afterGetAttributeUsedForSortByArray(\Magento\Catalog\Model\Config $catalogConfig, $options) { $customOption['newest_product'] = __('Newest Product'); $options = array_merge($customOption, $options); return $options; } } |
3 . Create Toolbar.php file in Vendor/ModuleName/Plugin/Product/ProductList
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | <?php namespace Vendor\ModuleName\Plugin\Product\ProductList; class Toolbar { public function aroundSetCollection( Toolbar $subject, \Closure $proceed, $collection ) { $currentOrder = $subject->getCurrentOrder(); if ($currentOrder == "newest_product") { $direction = $subject->getCurrentDirection(); $collection->getSelect()->order('created_at ' . $direction); } return $proceed($collection); } } |
Following the above steps, you can see the sort by newest product option in Magento 2 category page as shown below:
Related Post:
Get Weekly Updates
Never miss Magento tips, tricks, tutorials, and news.
Thank you for subscribing.
Something went wrong.