Magento 2: Add Product To Cart But Still Keep It In Wishlist

Add Product to cart but still keep it in wishlist - Magento tutorial

There is a question on magento.stackexchange about how to keep products in the wishlist after adding them to cart. Today, we will show you how to tackle this issue.

You can see the solution on our Youtube video or follow the following guidelines:

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();
    }
}

Therefore, we will use the plugin to change the function addToCart of the core.

Step 1: module.xml

<?xml version="1.0"?>
<!--
/**
 * Copyright © 2015 Magebuzz. All rights reserved.
 */
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/Module/etc/module.xsd">
    <module name="Magebuzz_Wishlistplus" setup_version="0.0.1" />
</config>

Step 2: registration.php

<?php

\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Magebuzz_Wishlistplus',
    __DIR__
);

Step 3: di.xml

<?xml version="1.0"?>
<!--
/**
 * @copyright Copyright (c) 2016 www.magebuzz.com
 */
-->
<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="mb_plugin_add_to_cart_after_add" type="Magebuzz\Wishlistplus\Plugin\ActionDelete" />
    </type>
</config>

Step 4: ActionDelete.php

<?php
/**
 * @copyright Copyright (c) 2016 www.magebuzz.com
 */

namespace Magebuzz\Wishlistplus\Plugin;

class ActionDelete
{
    public function beforeAddToCart(\Magento\Wishlist\Model\Item $subject, \Magento\Checkout\Model\Cart $cart, $delete) {
        return [$cart, false];
    }
}

After we ran the module Magebuzz_Wishlistplus, we can add items to their cart, but the product will not disappear.

To download Wishlist module, click on: Magebuzz Wishlist Plus for Magento 2

Comments