Set subscriber status in Magento programmatically

Chuck D picture Chuck D · Feb 25, 2011 · Viewed 14.3k times · Source

I am trying to write a module that syncs my newsletter subscribers in Magento with a external database. I need to be able to update the subscription status in Magento programmatically but I am having diffuculty getting the "setStatus" method in Magento to work. It does not throw any errors but the code does not seem to have any effect. Below is the code where I call the method:

$collection = Mage::getResourceModel('newsletter/subscriber_collection')->showStoreInfo()->showCustomerInfo();

foreach ($collection as $cust) {
    $cust->setStatus(1);
}

In theory, this should set the status of all of my subscribers to "subscribed". I could optionally change the argument sent to "setStatus" to any of the below ints for a different status.

1: Subscribed 2: Status Not Active 3: Unsubscribed

How to best change the subscriber status or get this code working?

Answer

panticz picture panticz · Sep 18, 2012

Here an import script:

<?php
require_once("./app/Mage.php");
Mage::app();

$subscribers = array('[email protected]', '[email protected]');

foreach ($subscribers as $email) {
    # create new subscriber without send an confirmation email
    Mage::getModel('newsletter/subscriber')->setImportMode(true)->subscribe($email);

    # get just generated subscriber
    $subscriber = Mage::getModel('newsletter/subscriber')->loadByEmail($email);

    # change status to "subscribed" and save
    $subscriber->setStatus(Mage_Newsletter_Model_Subscriber::STATUS_SUBSCRIBED);
    $subscriber->save();
}
?>