1
<?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

1 Answer 1

3

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
    }
}
10
  • can i use this wishlist.phtml file ? Jul 10, 2019 at 7:32
  • You want to add code in core file? Jul 10, 2019 at 8:03
  • no, i need custom module and file wishlist.phtml '' app/code/vendor/module/templates/catalog/product/view/addto/wishlist.phtml Jul 10, 2019 at 8:04
  • Do you have helper or block file of your custom module? Jul 10, 2019 at 8:05
  • not now, currently i'm just testing in vendor file then it works l'll create Jul 10, 2019 at 8:08

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.