0

I use this code to set the subscription status:

const STATUS_SUBSCRIBED     = 1;
const STATUS_NOT_ACTIVE     = 2;
const STATUS_UNSUBSCRIBED   = 3;
const STATUS_UNCONFIRMED    = 4;

...

$customer = Mage::getSingleton('customer/session')->getCustomer();
$customerID = $customer->getId();

$customerModel = Mage::getModel('customer/customer')
        ->setWebsiteId(Mage::app()->getStore()->getWebsiteId())
        ->load($customerID);

Mage::getModel('newsletter/subscriber')
        ->setCustomerId($customerModel->getId())
        ->setStatus(self::STATUS_SUBSCRIBED)
        ->setEmail("[email protected]")
        ->save();

But the state is not saved and the checkbox* is not getting set in the backend. What am I doing wrong?

*the checkbox I talk about is at: Customers -> manage customers -> 'enter a customer account' -> Newsletter

1 Answer 1

1

Below code worked for me --

in Guest case--

$email = "[email protected]";

$subscriber = Mage::getModel('newsletter/subscriber')->loadByEmail($email);
$subscriber->setStoreId(Mage::app()->getStore()->getId());
$subscriber->setSubscriberStatus(Mage_Newsletter_Model_Subscriber::STATUS_SUBSCRIBED);
$subscriber->setEmail($email);
$subscriber->setCustomerId(0);
$subscriber->save();

in case of customer email -

$email = "[email protected]";
$customerID = 1;

$subscriber = Mage::getModel('newsletter/subscriber')->loadByEmail($email);
$subscriber->setStoreId(Mage::app()->getStore()->getId());
$subscriber->setSubscriberStatus(Mage_Newsletter_Model_Subscriber::STATUS_SUBSCRIBED);
$subscriber->setEmail($email);
$subscriber->setCustomerId($customerID);
$subscriber->save();
6
  • Thanks so far, we are almost there!! It does work if I use STATUS_SUBSCRIBED, but not if I use STATUS_UNSUBSCRIBED ._. how can I unsubscribe a user?
    – Black
    Commented Oct 4, 2018 at 18:10
  • it works well for unsubscribed case with Mage_Newsletter_Model_Subscriber::STATUS_UNSUBSCRIBED Commented Oct 5, 2018 at 5:22
  • Nope, I tried it. Won't work. The checkbox is still set.
    – Black
    Commented Oct 5, 2018 at 7:19
  • can you paste your code for unsubscribed ? Commented Oct 5, 2018 at 7:21
  • It seems like I strictly have to write $subscriber = Mage::getModel('newsletter/subscriber')->loadByEmail($email); like you did, then it works! If I put loadByEmail($email) in a separate line e.g. $subscriber->loadByEmail($email); then it does not work. That was my culprit. But it does not work if I use another email adress then the one used to register the account.
    – Black
    Commented Oct 5, 2018 at 11:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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