Hiding the Wishlist Button if an Item is Already Added
In Magento version 1.9.1.0, you can easily hide the wishlist button or change it to a filled heart icon if a product is already in the current customer’s wishlist. To achieve this functionality, we’ll need to make some changes to your existing code.
The Current Implementation
The provided code snippet is almost correct:
<?php if ($this->helper('wishlist')->isAllow()) : ?>
<div class="ajax-wishlist">
<a href="#"
onclick='ajaxWishlist("<?php echo $this->helper('wishlist')->getAddUrl($_product) ?>","<?php echo $_product->getId()?>");return false;'
class="link-wishlist" title="Add to Wishlist"> <i class="fa fa-heart-o"></i> </a>
</div>
<?php endif; ?>
This code checks if the wishlist is enabled and then displays a link with an empty heart icon. Clicking this link will add the product to the customer’s wishlist.
The Issue with Dynamic Updates
You mentioned that you’d like to update the wishlist button dynamically from an empty heart to a filled heart as soon as an item is added. This requires real-time communication between the client and server, which Magento 1 doesn’t handle efficiently out of the box for this specific scenario.
A Better Approach: Use AJAX
To achieve dynamic updates without page reloads, we’ll use AJAX calls to update the button state after adding a product to the wishlist. Here’s how you can do it:
-
Add the Product to the Wishlist: When the customer clicks the “Add to Wishlist” button, an AJAX call is made to add the product to their wishlist.
-
Update the Button State: After successfully adding the item to the wishlist, send a response from the server with updated state information.
-
Update the Frontend: On the client side, use JavaScript to receive this response and update the button’s CSS class accordingly (empty heart vs filled heart).
Updating Wishlist Buttons on Homepage
To display only products that are not already in the current customer’s wishlist on pages like “New Arrivals” or “Most Viewed”, you can modify your code as follows:
<?php $wishlist = Mage::getModel('wishlist/item')->load($_product->getId(), 'product_id');
if (!($wishlist->getId())) { // If the product is not in the wishlist ?>
<a href="<?php echo $this->helper('wishlist')->getAddUrl($_product) ?>">
Add This
</a>
<?php } ?>
This code loads the wishlist item and checks if it exists for the current customer. If the getId() method doesn’t return a value, then the product is not in their wishlist.
Conclusion
In summary, to hide or change the wishlist button state based on whether an item is already in the current customer’s wishlist, you’ll need to use AJAX calls for real-time updates. If you want to display only products that aren’t in a customer’s wishlist (like on homepage lists), modify your existing code with the provided snippet.
Visit our Magento development services page to learn more about other advanced features and integrations we offer for Magento stores.