Magento – Returning wishlist item collection for currently logged in user

collection;magento2product-listwishlist

I'm trying to return the wishlist item collection for the currently logged in user and iterate over the collection.

I've tried the following, but I get an empty collection.

<?php /* @escapeNotVerified */
                                    $_in_wishlist = false;
                                    echo count($this->helper('Magento\Wishlist\Helper\Data')->getWishlistItemCollection());
                                    foreach ($this->helper('Magento\Wishlist\Helper\Data')->getWishlistItemCollection() as $_wishlist_item){
                                        if($_product->getId() == $_wishlist_item->getProduct()->getId()){
                                            $_in_wishlist = true;
                                            break;
                                        }
                                    } ?>

I've also tried, getWishlist()->getItemCollection() but this doesn't return anything either.

I'm logged in and I have 2 items in my wishlist. Could this be to do with caching?

Best Answer

To do so you need to use the Magento\Wishlist\Controller\WishlistProviderInterface interface.

Inject this class in your constructor:

protected $wishlistProvider;

public function __construct(
    ...
    \Magento\Wishlist\Controller\WishlistProviderInterface $wishlistProvider
) {
    $this->wishlistProvider = $wishlistProvider;
    ...
}

Then you can call the following to get the current logged in user wishlist:

$currentUserWishlist = $this->wishlistProvider->getWishlist();
if ($currentUserWishlist) {
    $wishlistItems = $currentUserWishlist->getItemCollection();
}
Related Topic