Using a custom controller to change Wishlist button(icon) color once the product added to Wishlist.
app/code/vendor/module/Controller/Index/Wishlist.php
<?php
namespace Vendor\Module\Controller\Index;
class Wishlist extends \Magento\Framework\App\Action\Action {
public function __construct(
\Magento\Framework\App\Action\Context $context,
\Magento\Wishlist\Helper\Data $wishlistHelper,
\Magento\Framework\Controller\Result\JsonFactory $jsonFactory
) {
parent::__construct($context);
$this->wishlistHelper = $wishlistHelper;
$this->jsonFactory = $jsonFactory;
}
public function execute() {
$result = $this->jsonFactory->create();
$data = $this->wishlistHelper->getWishlistItemCollection()->getData();
return $result->setData(['status' => 200, 'items' => $data]);
}
}
app/code/vendor/module/etc/frontend/routes.xml
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
<router id="standard">
<route frontName="customwishlist" id="customwishlist">
<module name="Devcrew_Wishlistcustom"/>
</route>
</router>
Add the following Script in theme's list.phtml or wishlist.phtml Depend upon Theme :
<script>
require(['jquery'], function($){
jQuery.ajax({
url: '<?php echo $this->getUrl('customwishlist/index/wishlist') ?>',
method: 'get',
dataType: 'json',
success: function(data) {
var wislistAddesCheckData = data;
var itemLenth = wislistAddesCheckData.items.length;
for(i=0;i<itemLenth; i++){
var wislistAddedProductId = wislistAddesCheckData.items[i].product_id;
$(".product-id-"+wislistAddedProductId).attr('src','<?php echo $img; ?>');
}
}
});
});
</script>
Add this class in wishlist Div or Image:
class="product-id-<?php echo $block->getProduct()->getId();?>"