Magento 2.1 – Remove Product from Wishlist Using Customer ID and Product ID

magento-2.1wishlist

How to remove product from wishlist using customer id and product id programmatically? I searched alot about it, But the results are remove wishlist item using item id only. So is there any way to remove wish list item using customer id and product id only?

Please suggest me how can I get this done.

Thanks.

Best Answer

Unfortunately Magento didn't provide ready to use function to delete item from wishlist. But you can use follow code to do this, I tested it and all works fine at my local Magento.

protected $wishlist;

public function __construct(
    \Magento\Wishlist\Model\Wishlist $wishlist
) {
    $this->wishlist = $wishlist;
}

public function execute()
{
    $customerId = 1;
    $productId = 6;
    $wish = $this->wishlist->loadByCustomerId($customerId);
    $items = $wish->getItemCollection();

    /** @var \Magento\Wishlist\Model\Item $item */
    foreach ($items as $item) {
        if ($item->getProductId() == $productId) {
            $item->delete();
            $wish->save();
        }
    }
}
Related Topic