Magento 2.3 – How to Check if Current Product Is Already Added to Wishlist

magento2.3productswishlist

<?php 
 echo "<pre>";    
 print_r($this->helper('Magento\Wishlist\Helper\Data')->getWishlistItemCollection()->addFieldToFilter('product_id', $_product->getId())->count());
 die();
 ?>

I am using this Query to get wish list added product Count but it returns always '0', my current product is already added into wish list !! How to solve this issue?

vendor/magento/module-wishlist/view/frontend/templates/catalog/product/view/addto/wishlist.phtml

Currently, I am testing with 'wishlist.phtml' vendor file

Best Answer

You can try to use this below code :

protected $wishlist;
protected $registry;

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

public function yourFunction(){
    $customer_id = 1;
    $wishlist_collection = $this->wishlist->loadByCustomerId($customer_id, true)->getItemCollection();
    $current_product = $this->_registry->registry('current_product');
    foreach ($wishlist_collection as $item) {
        if($current_product->getId() == $item->getProduct()->getId())
        {
            // current item added in wishlist
        } else {
            // current item not added in wishlist
        }
    }
}

UPDATE :


Object Manager Method :

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$session = $objectManager->get('Magento\Customer\Model\Session');
$customer_id = $session->getCustomer()->getId(); 


$wishlist_collection = $objectManager->get('Magento\Wishlist\Model\Wishlist')->loadByCustomerId($customer_id, true)->getItemCollection();
$current_product =  $objectManager->get('Magento\Framework\Registry')->registry('current_product');
foreach ($wishlist_collection as $item) {
    if($current_product->getId() == $item->getProduct()->getId())
    {
        // current item added in wishlist
    } else {
        // current item not added in wishlist
    }
}
Related Topic