How to check if a product is already on the wishlist in Magento 2?

Try this code..

<?php
$wishlistHelper = $this->helper('Magento\Wishlist\Helper\Data');

if($wishlistHelper->isAllow()){

$wishlistCollection = $wishlistHelper->getWishlistItemCollection();     
foreach ($wishlistCollection as $_wishlist_item) {
   $in_wishlist = false;
   if ($_product->getId() == $_wishlist_item->getProduct()->getId()) {
       $in_wishlist = true; break;
   }
}
?>

if(!empty($_in_wishlist) && $_in_wishlist){ ?>
  <li><span class="in-wishlist"><?= __('Already in Wishlist')?></span></li>
<?php }else{ ?>
  <li><a href="<?= $wishlistHelper->getAddUrl($_product) ?>" class="link-wishlist"><?= __('Add to Wishlist') ?></a></li>
<?php } ?>
<?php } ?>

As far as I know, we can use \Magento\Wishlist\Helper\Data to check if a product is already on the wishlist.

/** @var \Magento\Wishlist\Helper\Data $wishlistHelper **/

$wishlistHelper->getWishlistItemCollection()
              ->addFieldToFilter('product_id', $_product->getId());

Remember to inject this class in your construction.


<?php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$_in_wishlist = false;
foreach ($this->helper('Magento\Wishlist\Helper\Data')->getWishlistItemCollection() as $_wishlist_item){
    if($_product->getId() == $_wishlist_item->getProduct()->getId()){
        $_in_wishlist = true;
    }
}
$customerSession = $objectManager->get('Magento\Customer\Model\Session');
if($customerSession->isLoggedIn()) 
{
    if($_in_wishlist) { ?>
        <a href="#" data-post="#" data-action="already-in-wishlist"><span class="wish-list lineheight48"><img data-alt-src="<?php echo $block->getViewFileUrl('images/icons/body-shop-icons_wishlist_filled.svg'); ?>" width="38" src='<?php echo $this->getViewFileUrl('images/icons/icon-wishlist-black.svg'); ?>' alt="Wish list"></span></a>
    <?php } else { ?>
        <a href="#" data-post='<?php echo $this->helper('Magento\Wishlist\Helper\Data')->getAddParams($_product) ?>' class="action towishlist" data-action="add-to-wishlist"><span class="wish-list lineheight48"><img data-alt-src="<?php echo $block->getViewFileUrl('images/icons/body-shop-icons_wishlist_filled.svg'); ?>" width="38" src='<?php echo $this->getViewFileUrl('images/icons/icon-wishlist.svg'); ?>' alt="Wish list"></span></a>
    <?php } ?>
    <?php 
} else { ?> 

    <a href="#" data-post='<?php echo $this->helper('Magento\Wishlist\Helper\Data')->getAddParams($_product) ?>' class="action towishlist" data-action="add-to-wishlist"><span class="wish-list lineheight48"><img data-alt-src="<?php echo $block->getViewFileUrl('images/icons/body-shop-icons_wishlist_filled.svg'); ?>" width="38" src='<?php echo $this->getViewFileUrl('images/icons/icon-wishlist.svg'); ?>' alt="Wish list"></span></a>
<?php
}
?>