Customer Experience Insights

How to interact with a customer wish list in Magento 2

Written by Christopher Liddell | Aug 17, 2022

The customer wishlist is an important tool to offer a better user experience, increase sales and obtain more data from the customer in order to model and analyze their preferences.

In Magento 2, you can get and modify the customer's wishlist programmatically  with the following code:

<?php
namespace Imagineer\Wishlist\Helper;
use \Magento\Framework\App\Helper\AbstractHelper;
use \Magento\Framework\App\Helper\Context;
use \Magento\Customer\Model\Session;
use \Magento\Wishlist\Model\Wishlist;
use \Magento\Catalog\Api\ProductRepositoryInterface;


class WhishlistHelper extends AbstractHelper {
  private $session;
  private $wishlist;
  private $productRepository;


  /**
  * @param \Magento\Framework\App\Helper\Context $context
  * @param \Magento\Wishlist\Model\Wishlist $wishlistHelper
  * @param \Magento\Customer\Model\Session $session
  * @param \Magento\Catalog\Api\ProductRepositoryInterface $productRepository
  */
  public function __construct(
    Context $context,
    Wishlist $wishlist,
    Session $session,
    ProductRepositoryInterface $productRepository

  ) {
    parent::__construct($context);
    $this->wishlist = $wishlist;
    $this->session = $session;
    $this->productRepository = $productRepository;
  }


  public function getCustomerId(){
    if(!$this->session->isLoggedIn()){
      return false;
    }
    return $this->session->getCustomerId();
  }


  public function isInWishlist($productId){
    $customerId = $this->getCustomerId();
    if(!$customerId){
      return false;
    }

    $wishlistCollection = $this->wishlist->loadByCustomerId($customerId)
->getItemCollection();
    $inWishlist = false;
    foreach ($wishlistCollection as $wishlist_item) {
      if($wishlist_item->getProduct()->getId() == $productId){
        $inWishlist = true;
        break;
      }
    }
    return $inWishlist;
  }

  public function addProductToWishlist($productId){
    if(!$this->isInWishlist($productId)){
      return false;
    }

 $product = $this->_productRepository->getById($productId);
if($product == null){
return false;
}
 $wishlist = $this->wishlist->loadByCustomerId($customerId);
$wishlist->addNewItem($product);
$wishlist->save();

  return true;
  }

  public function removeProductFromWishlist($productId){
    if(!$this->isInWishlist($productId)){
      return false;
    }

 
 $product = $this->_productRepository->getById($productId);
if($product == null){
return false;
}
 
 $wishlist = $this->wishlist->loadByCustomerId($customerId);
$items = $wishlist->getItemCollection();
 foreach ($items as $item) {
if ($item->getProductId() == $productId) {
$item->delete();
$wish->save();
}
}

return true;
  }
}

 

The functions in the above class do the following:

  • getCustomerId(): Gets the #id of the current client. This behavior can be overridden depending on how you want to select the client.
  • isInWishlist($productId): Find out if the product with the specified #id is in the wishlist.
  • addProductToWishlist($productId): Adds the product with the specified #id to the customer's wishlist.
  • removeProductFromWishlist($productId): Remove the product with the specified #id from the customer's wishlist.


It is also possible to display the customer's wishlist information in the frontend with javascript in the following ways:

var wishlist = JSON.parse(localStorage.getItem('mage-cache-storage')).wishlist;

var items = wishlist.items;




Or using the following file as a base:

vendor/magento/module-wishlist/view/frontend/web/js/view/wishlist.js

define([
    'uiComponent',
    'Magento_Customer/js/customer-data'
  ], function (Component, customerData) {
  'use strict';

  return Component.extend({
    initialize: function () {
      this._super();
      this.wishlist = customerData.get('wishlist');
    }
  });
});

Additionally, if you want to create a button to add products to the wishlist, you can do it in your template   (such as Magento_Catalog/templates/products/list/addto/wishlist.phtml ) with the following code:

<?php
echo $block->getLayout()
->createBlock('Magento\Wishlist\Block\Catalog\Product\ProductList\Item\AddTo\Wishlist')
->setProduct($_product)
->setTemplate("Magento_Wishlist::catalog/product/list/addto/wishlist.phtml")->toHtml();
?>

I hope this article has been helpful to create components that interact with the customer's wishlist.