I want to add wishlist remove link if product is already on wishlist in Magento2.

I have tried but it's not working when fullpage_cache is On

1. enter image description here

2. enter image description here

3. enter image description here

有帮助吗?

解决方案

  • add code for di.xml
<preference for="Magento\Wishlist\CustomerData\Wishlist" type="Vendor\YourModule\CustomerData\Rewrite\Wishlist"/>
  • create file Vendor\YourModule\CustomerData\Rewrite\Wishlist.php

namespace Vendor\YourModule\CustomerData\Rewrite;

/**
 * Wishlist section
 */
class Wishlist extends \Magento\Wishlist\CustomerData\Wishlist
{


    /**
     * {@inheritdoc}
     */
    public function getSectionData()
    {
        $counter = $this->getCounter();
        return [
            'counter' => $counter,
            'added' => $this->getItemsAdded(),
            'items' => $counter ? $this->getItems() : [],           
        ];
    }

    public function getItemsAdded(){
        $collection = $this->wishlistHelper->getWishlistItemCollection();
        $collection->clear()->setInStockFilter(true)->setPageSize(false);
        $items      = array();

        foreach ($collection as $item){
            $items[$item->getProductId()] =   json_decode($this->wishlistHelper->getRemoveParams($item, true));
        }
        return $items;
    }   
}

  • use code js for get product added and mark product

var added = jQuery.parseJSON(localStorage.getItem('mage-cache-storage')).wishlist.added

var AddedWishlist = jQuery('.towishlist').data('wishlist');

if(AddedWishlist && added[AddedWishlist.data.product]){
   jQuery('.towishlist')    
        .addClass('your_class')
        .attr('title', 'Remove from wishlist')
        .html(jQuery('<span>').html('Remove from wishlist');


}                       



其他提示

<script>
   require(['jquery'], function($){
    var added = $.parseJSON(localStorage.getItem('mage-cache-storage')).wishlist.added;
    var AddedWishlist = jQuery('.towishlist').attr('data-post');
    var AddedWishlistArray = JSON.parse(AddedWishlist);


    if(AddedWishlist && added[AddedWishlistArray.data['product']]){
        $('.towishlist').addClass('.in-wishlist').attr('title', 'Remove from wishlist').attr('data-post',JSON.stringify(added[AddedWishlistArray.data['product']])).html("<span>Remove from wishlist</span>");
    }        

   });
</script>

许可以下: CC-BY-SA归因
scroll top