8

I am developing this custom xml export/import. In magento 2 how can I check if a customer is subscribed to newsletter? Right now I am loading the customer factory.

\Magento\Framework\App\ObjectManager::getInstance()->create('Magento\Customer\Model\Customer');

But this does not give information about newsletter is there another model I have to load?

19

First inject the \Magento\Newsletter\Model\Subscriber class in your constructor:

protected $_subscriber;

public function __construct(
    ...
    \Magento\Newsletter\Model\Subscriber $subscriber
    ...
){
    ...
    $this->_subscriber= $subscriber;
    ...
}

Then you have two possible cases

Assuming your have the customer email

Then in your code you can call the following code to check whether or not the customer is subscribed to the newsletter:

$checkSubscriber = $this->_subscriber->loadByEmail($customerEmail);

if ($checkSubscriber->isSubscribed()) {
    // Customer is subscribed
} else {
    // Customer is not subscribed
}

Assuming you have the customer id

You can call the following code:

$checkSubscriber = $this->_subscriber->loadByCustomerId($customerId);

if ($checkSubscriber->isSubscribed()) {
    // Customer is subscribed
} else {
    // Customer is not subscribed
}
  • where would you execute this code? – styzzz Aug 27 at 19:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.