Newsletters: Codex – Add Subscriber

You can manually add/remove subscribers with the WordPress Newsletter plugin if you want to create your own subscribe form.

If you have a custom form on your site custom created or from another plugin, you can accept subscriptions by capturing an email address and manually adding the email as a subscriber with a bit of PHP code.

Add a Subscriber

You may have a custom form on your site like this:

<form action="" method="post">
	<label>Email Address:<br/>
	<input type="text" name="email" value="<?php echo esc_attr(stripslashes($_POST['email'])); ?>" />
	</label><br/>
	<label><input type="checkbox" name="subscribe" value="1" /> Subscribe</label><br/>
	<input type="submit" name="submit" value="Submit" />
</form>

The form looks like this:

The form above is just an example but it could be any custom form you may have. As you can see, this custom form captures an email address and has a ‘Subscribe‘ checkbox for a user to choose to subscribe.

We can now take the posted data from the form and attempt to save the email address as a Newsletter plugin subscriber if the ‘Subscribe‘ checkbox was ticked by the user. Here is some PHP code to handle the subscription:

if (!empty($_POST)) {
	if (!empty($_POST['subscribe'])) {
		if (class_exists('wpMail')) {
			$wpMail = new wpMail();
			global $Subscriber;
			$data = array('email' => $_POST['email'], 'list_id' => array(1,2));

			if ($Subscriber -> optin($data, false)) {
				//success
			} else {
				print_r($Subscriber -> errors);
			}
		}
	}
}

So you’re mainly using the $Subscriber -> optin() function. The function itself will validate the data and put any errors into $Subscriber -> errors.

The first parameter of the optin() function contains an array of data. It requires an “email” value with the valid email address and a “list_id” value which is an array itself with the IDs of the mailing lists to subscribe to. Even if you’re just subscribing the email to one list, it still needs to be an array.

The second parameter of the optin() function simply tells the plugin to validate or not. It is recommended that you set this to “false” so that it doesn’t throw unnecessary errors. The plugin will do the needed validation on the email address even if this is set to false.

Website & Email Hosting

Get the best website & email hosting for speed, security, and peace of mind. No restrictions. Freedom to do what you need in order to run your business.

Host Now

Pin It on Pinterest