Magento 2 – Get Wishlist Collection by Customer ID

customermagento2productswishlist

I am trying to get the wishlist products collection of a particular customer by the customer Id. but it is not working. I am using the following code :

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$wishlist = $objectManager->get('\Magento\Wishlist\Model\Wishlist');
$wishlist_collection = $wishlist->loadByCustomerId($userId, true)->getItemCollection();

Best Answer

Try this

private $wishlist;

public function __construct(
    ...
    \Magento\Wishlist\Model\Wishlist $wishlist
) {
    $this->wishlist = $wishlist;
    ...
}

...
$customer_id = 1;
$wishlist_collection = $this->wishlist->loadByCustomerId($customer_id, true)->getItemCollection();

foreach ($wishlist_collection as $item) {
    print_r($item->getProduct()->getName());
}