Using a plugin, you can remove the invalid wishlist item from the collection and from the database. Create a etc/frontend/di.xml
in your module (the module name is YourNamespace_Wishlist
in this example):
<?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\Wishlist">
<plugin name="yournamespace_wishlist" type="YourNamespace\Wishlist\Plugin\WishlistPlugin" />
</type>
</config>
Then, create the plugin (Plugin/WishlistPlugin.php
):
<?php
declare(strict_types=1);
namespace YourNamespace\Wishlist\Plugin;
use Magento\Framework\Exception\LocalizedException;
use Magento\Wishlist\Model\Wishlist as Subject;
use Magento\Wishlist\Model\Item as WishlistItem;
use Magento\Wishlist\Model\ResourceModel\Item as WishlistItemResource;
use Magento\Wishlist\Model\ResourceModel\Item\Collection as WishlistItemCollection;
class WishlistPlugin
{
/**
* @var WishlistItemResource
*/
private $wishlistItemResourceModel;
public function __construct(
WishlistItemResource $wishlistItemResourceModel
) {
$this->wishlistItemResourceModel = $wishlistItemResourceModel;
}
/**
* Remove items without existing products from collection and from database
*
* @param Subject $subject
* @param WishlistItemCollection $wishlistItemCollection
* @return WishlistItemCollection
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function afterGetItemCollection(
Subject $subject,
WishlistItemCollection $wishlistItemCollection
): WishlistItemCollection {
foreach ($wishlistItemCollection as $key => $wishlistItem) {
/** @var WishlistItem $wishlistItem */
try {
$wishlistItem->getProduct();
} catch (LocalizedException $e) {
$wishlistItemCollection->removeItemByKey($key);
$this->wishlistItemResourceModel->delete($wishlistItem); // phpcs:ignore MEQP1.Performance.Loop
}
}
return $wishlistItemCollection;
}
}
It's a Commerce Edition (aka Enterprise Edition) problem only - in the OpenSource edition we have a foreign key to the product entity.