How to add new product to particular customer's wishlist in Magento2?
-
07-01-2021 - |
Question
Can anyone help me out? I want to add new products to the particular customer's wishlist automatically.
Solution
<?php
$customerId = 2;
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$productCollection = $objectManager- >create('Magento\Catalog\Model\ResourceModel\Product\Collection');
$collection = $productCollection->addAttributeToSelect('*')
->setPageSize(3)
->addAttributeToSort('updated_at', 'DESC')
->load();
foreach($collection as $product){
$product = $objectManager->create('Magento\Catalog\Model\Product')->load($product->getId());
$wishList = $objectManager->get('\Magento\Wishlist\Model\WishlistFactory');
$wishlistAdd = $wishList->create()->loadByCustomerId($customerId, true);
$wishlistAdd->addNewItem($product);
$wishlistAdd->save();
}
?>
I highly recommend to inject Magento\Catalog\Model\Product
and Magento\Wishlist\Model\WishlistFactory
in your constructor.
This is for your just quick snippet.
Hope it will help you.
OTHER TIPS
You have use Magento\Wishlist\Model\Wishlist
class.
First you need to load a customer wishlist by calling function loadByCustomerId()
Then add a new item to wish list using method addNewItem
Code:
<?php
namespace {NameSpaceofClass};
class {Classname}{
protected $_wishlistFactory;
public function __construct(
\Magento\Wishlist\Model\WishlistFactory $wishlistFactory
)
{
$this->_wishlistFactory = $wishlistFactory
}
public function addAnewProduct()
{
$wishlist = $this->_wishlistFactory->create();
$wishlist->loadByCustomerId(15); //15 is Customer Id
if($wishlist){
$wishlist->addNewItem(25); // 25 Product id
}
}
}
Note that:
addNewItem has 3 parameters
$product
canProduct id OR product object
which should be instance\Magento\Catalog\Model\Product
.$buyRequest
, it should be instance\Magento\Framework\DataObject or array or string or null
.
3. $forciblySetQty
boolean true/false forcefully set qty.
This is the code I have used in my controller
<?php
namespace Wishorder\Asorder\Controller\Index;
use \Magento\Framework\App\Action\Context;
use \Magento\Framework\View\Result\PageFactory ;
use \Magento\Wishlist\Model\WishlistFactory ;
class Index extends \Magento\Framework\App\Action\Action
{
protected $resultPageFactory;
protected $wishlistFactory;
public function __construct(Context $context
\Magento\Framework\View\Result\PageFactory $resultPageFactory,
\Magento\Wishlist\Model\WishlistFactory $wishlistFactory
)
{
$this->resultPageFactory = $resultPageFactory;
$this->wishlistFactory = $wishlistFactory;
parent::__construct($context);
}
public function execute()
{
$wishlist = $this->wishlistFactory->create();
$wishlist->loadByCustomerId(1); //15 is Customer Id
$resultPage = $this->resultPageFactory->create();
if($wishlist){
$wishlist->addNewItem(25); // 25 Product id
$wishlist->save(); // 25 Product id
}
return $this->resultPageFactory->create();
}
}
?>