Magento Tips & Tricks

Magento 2: Working with Wishlist

Magento 2 wishlist – list of products that a customer can share with anyone. Another purpose is to keep products you want to buy at a later date. By default it has some limitations and theme developer often need to customize it.

  • Following samples was tested on magento 2.3.0
  • You need to update Vendor/Module in filenames and code to correct values
  1. Number of items in wishlist sidebar
  2. “Add to wishlist” without redirecting to wishlist page
  3. Remove “items” text in wishlist top links
  4. Work with wishlist items in javascript

Number of items in Magento 2 wishlist sidebar

By default you can see 3 last added wishlist items in sidebar. This number is hardcoded in Magento\Wishlist\CustomerData\Wishlist class. There is no corresponding option in admin panel. To override it we will use dependency injection functionality.

– add following line in module di.xml to tell magento to use our class instead of standard one.
Filename: Vendor/Module/etc/frontend/di.xml

– create the class. We override only getItems function, which is used to get wishlist items. If you want to limit wishlist collection, you need to use setPageSize function.
Filename: Vendor/Module/CustomerData/Wishlist.php

“Add to wishlist” without redirecting to wishlist page

When you click “Add to Wishlist” button, it redirect you wishlist page. To fix it we need to override Magento\Wishlist\Controller\Index\Add controller.

– add following line in module di.xml to tell magento to use our class instead of standard one.
Filename: Vendor/Module/etc/frontend/di.xml

– create the class. Basically it duplicate original method, only $resultRedirect updated to use referer url
Filename: Vendor/Module/Controller/Index/Add.php

Remove “items” text in wishlist top links

It can be done in several ways.

– you can use translation file. Like app/design/frontend/Magento/luma/i18n/en_US.csv

– you can override createCounter function in Vendor/Module/CustomerData/Wishlist.php

– you can update link template ( by default it is view/frontend/templates/link.phtml ) and change

to

Work with wishlist items in javascript

You might want to get wishlist items array in frontend. For example, to mark products that already in customer’s wishlist. It can be done with help of customer-data object. customer-data updated via ajax, so it might not have the wishlist information at the initialization. Luckily customer data use knockout observable functionality, so we can subscribe to data update event.

Sample below use wishlist items array to add “selected” class to wishlist button. You can use it to decorate button.

– create wishlist_items.js
Filename: Vendor/Module/view/frontend/web/js/wishlist_items.js

– add initialization code to your wishlist template

Leave a Reply

Your email address will not be published. Required fields are marked *