Add a product to wishlist of Customers in particular group
-
07-01-2021 - |
Question
I am trying to add a product to wishlist of all customer in a particular group.
Currently I have added products to a particular customer's wishlist.
That I have to add to a particular group of customers.
Can anyone guide me regarding this ?
Solution
update your class constructor like this:
protected $_wishlistRepository;
protected $_productRepository;
protected $_customerFactory;
public function __construct(
...
\Magento\Wishlist\Model\WishlistFactory $wishlistRepository,
\Magento\Catalog\Api\ProductRepositoryInterface $productRepository,
\Magento\Customer\Model\CustomerFactory $customerFactory
) {
$this->_wishlistRepository= $wishlistRepository;
$this->_productRepository = $productRepository;
$this->_customerFactory = $productRepository;
...
}
Then in you can do the following,
/** set customer group id in filter of customer collection**/
$customerCollection = $this->_customerFactory->create()->getCollection()->addAttributeToSelect('*')->addFieldToFilter('group_id', 4);
foreach($customerCollection as $customer)
{
$customerId = $customer->getCustomerId();
try {
$product = $this->_productRepository->getById($productId);
} catch (NoSuchEntityException $e) {
$product = null;
}
$wishlist = $this->_wishlistRepository->create()->loadByCustomerId($customerId, true);
$wishlist->addNewItem($product);
$wishlist->save();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange