I'm trying to add an active class when product is in wishlist.

I tried below code.

    echo $_product->getId();
    $wishlist = $this->helper('Magento\Wishlist\Helper\Data')->getWishlistItemCollection()->addFieldToFilter('product_id', $_product->getId());


                 <div class="cdz-product-wishlist show-tooltip">
                            <?php if ($this->helper('Magento\Wishlist\Helper\Data')->isAllow() && $showCompareWishlist): ?>
                                <a href="#"
                                   class="action towishlist"
                                   title="<?php echo $block->escapeHtml(__('Add to Wish List')); ?>"
                                   aria-label="<?php echo $block->escapeHtml(__('Add to Wish List')); ?>"
                                   data-post='<?php /* @escapeNotVerified */ echo $block->getAddToWishlistParams($_product); ?>'
                                    <span><?php /* @escapeNotVerified */ echo __('Add to Wish List') ?></span>
                            <?php endif; ?> 

If I dump collection data then it returns me all products which are currently in wishlist but after I filter collection with product_id then it returns always first array.

But product ID is printing correctly.

Does anyone has idea what's issue here ?

2 Answers 2

After spending an hour at last I ended up creating array of wishlist
products and match current product id using in_array. 

Still if you have better solution I'm open for it.

      <a onclick="addToWishList('<?php echo $product['product_id']; ?>');$(this).find('img').toggleClass('active');">
        <img class="wishlist-icon icon-empty <?php echo !$product['in_wishlist'] ? 'active' : ''; ?>" src="/image/wishlist-empty.svg">
        <img class="wishlist-icon icon-full <?php echo $product['in_wishlist'] ? 'active' : ''; ?>" src="/image/wishlist-full.svg">

Your Answer

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

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