Magento 2 – Keep Wishlist Items

controllersmagento2wishlist

I need to keep the wishlist items after the customer have added them to the cart.

Where is the actual removal being done in the code?
I'm trying to track the call, but gets lost in the post being made in Wishlist.php in getAddAllToCartParams() method.

Best Answer

In app/code/Magento/Wishlist/Controller/Index/Cart.php in the execute() method the following code is what adds the item to the cart and removes it from the wishlist:

$item->addToCart($this->cart, true);

The addToCart() method is declared in app/code/Magento/Wishlist/Model/Item.php and the second parameter is what triggers the wishlist deletion. If you set it to false it won't delete the item from the wishlist:

/**
 * Add or Move item product to shopping cart
 *
 * Return true if product was successful added or exception with code
 * Return false for disabled or unvisible products
 *
 * @param \Magento\Checkout\Model\Cart $cart
 * @param bool $delete  delete the item after successful add to cart
 * @return bool
 * @throws \Magento\Catalog\Model\Product\Exception
 */
public function addToCart(\Magento\Checkout\Model\Cart $cart, $delete = false)
{
    ...
    if ($delete) {
        $this->delete();
    }
}

To avoid the auto delete behavior I suggest you create a plugin on the app/code/Magento/Wishlist/Model/Item.php class:

vendor\Module\etc\di.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="\Magento\Wishlist\Model\Item">
        <plugin name="disableAutoDelete" type="Vendor\Module\Plugin\DisableAutoDelete" />
    </type>
</config>

Then in your Plugin/DisableAutoDelete.php file you can do:

<?php
    namespace Vendor\Module\Plugin;
    
    class DisableAutoDelete
    {
        public function beforeAddToCart(\Magento\Wishlist\Model\Item $subject, \Magento\Checkout\Model\Cart $cart, $delete) {
            return [$cart, false];
        }
    }
?>
Related Topic