Drupal Simplenews: Automatically Subscribe New Users to a Newsletter

One of the sites I am setting up requires that all users be subscribed to a certain newsletter (or maybe two, depending on who they are) via Simplenews when they create their accounts (actually, their accounts are automatically created via LDAP... but that's another story).

Looking around, I found this post explaining how you might be able to auto-subscribe new users, and it led me to look up Simplenews' simplenews_subscribe_user() function.

Basically, you can add a line like the following in your custom module's hook_user() function, on the 'insert' $op (for Drupal 6):

<?php
 
// simplenews_subscribe_user(<email>, <tid_of_newsletter>, <send_confirmation_email_boolean>, <source_of_subscription>, <language>)
 
simplenews_subscribe_user($account->mail, 45, $confirm = FALSE, $source = 'action', NULL);
?>

Additionally, you can subscribe ALL of your site's users (or whatever subset you choose, via your own logic) to a Simplenews newsletter using the following PHP snippet (you can just paste this in Devel's 'Execute PHP Code' block):

<?php
$uids_to_update
= array(0, 1, 2);

foreach (
$uids_to_update as $uid) {
 
$account = user_load($uid);
 
simplenews_subscribe_user($account->mail, 45, $confirm = FALSE, $source = 'action', NULL);
}
?>

I grabbed a list of all the active uids on the site using views, turned them into an array (used quick regex in TextMate to turn a line-broken list into value, value, value...), then used the code above (with my own array in it) to subscribe all active users to the newsletter.

Comments

Chris Cohen's picture

Nice write-up Jeff. I do have one question though: is it necessary to call user_load() for each user? Supposing you have several hundred thousand users, this could take a very long time to complete. As far as I can see, given the user's uid, we just need the email address to pass to simplenews_subscribe_user() so maybe a simple SELECT mail FROM users WHERE uid = %d might be quicker?

Jeff Geerling's picture

That would be an excellent optimization; for my purposes, I only had a couple hundred users, so doing a user_load() didn't kill me. (I have one site where some of the pages do full node_loads() over three hundred times per page load... but there was no other/better way, so we cache those pages :).

Check out my personal website: www.lifeisaprayer.com.

Tim Wooten's picture

I could not get this code to work but found that simplenews comes with a simplenews actions submodule that works well. Simply set up a new action to subscribe a new user to the newsletter, then a trigger to do the action when a new user is created.

Add new comment