1

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();

2 Answers 2

7

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());
}
2
  • Why wishlist does not update immediately when i add/remove product from/to wishlist? I can see it updated on magento wishlist page but not on the page where i have written this code. It refresh data after i refresh page 4-5 times. I am working on local.
    – Khushbu
    May 23, 2019 at 5:34
  • @Dinesh Yadav, I want to collect wishlist data for all customers as a CSV. Please guide me.
    – MagentoDev
    Dec 26, 2019 at 4:37
0

Try to create a block class as shown below :

class Wishlist extends \Magento\Framework\View\Element\Template
 {

/**
 * @var CollectionFactory
 */
protected $_wishlistCollectionFactory;

public function __construct( 
    -------------,

    \Magento\Wishlist\Model\ResourceModel\Item\CollectionFactory $_wishlistCollectionFactory
)
{
   $this->_wishlistCollectionFactory = $_wishlistCollectionFactory;

}

public function getWishlistForCustomer($customerId)
{
  return $this->_wishlistCollectionFactory->create()
                ->addCustomerIdFilter($customerId);
}

}
4
  • Can you elaborate your answer to display product names from wishlist? I use code foreach ($wishlist_collection as $item) { print_r($item->getProduct()->getName()); } but i can not get data.
    – Khushbu
    May 23, 2019 at 6:31
  • I solved my issue by using code from this link: magento.stackexchange.com/questions/250483/…
    – Khushbu
    May 23, 2019 at 7:12
  • You can simply get the data of wishlist from $this->_wishlistCollectionFactory->create(); function and add the output data in a csv using fputcsv() function of php Dec 27, 2019 at 6:00
  • @Dinesh Yadav, Can you please share me the sample code on getting wishlist collection as a CSV file?
    – MagentoDev
    Dec 29, 2019 at 11:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.