Noptin provides a built-in function add_noptin_subscriber()
that allows developers to add new subscribers directly from their codebase.
This function is handy when integrating with custom forms, CRMs, or external APIs.
Function Overview
/**
* Inserts a new subscriber into the database.
*
* @param array $fields Associative array of subscriber data.
* @return int|string Subscriber ID on success or error message on failure.
*/
add_noptin_subscriber( array $fields );
At a minimum, $fields
must include a valid email address.
add_noptin_subscriber(
array(
'email' => '[email protected]',
)
);
You may pass additional fields to enrich the subscriber record. Here are some common and useful keys:
Field | Description | Example |
---|---|---|
name | Full name of the subscriber. You can also specify this as first_name and last_name if you don’t want to specify the full name. | Jon Doe |
status | One of: subscribed, unsubscribed, pending, bounced, or blocked. Defaults to pending if double opt-in is enabled, subscribed otherwise. | subscribed |
tags | Comma-separated string or array of tags. | woocommerce, customer |
source | Source of the subscription | WooCommerce |
language | Language code. Automatically set if using WPML or Polylang. | en_US |
ip_address | IP address of the subscriber. | 8.8.8.8 |
conversion_page | URL of the page where the subscription happened. | https://example.com/sign-up/ |
update_existing | Whether or not to update the existing subscriber if one already exists. | true |
TIP:
You can also pass any custom fields defined in your Noptin configuration.
Example Usage
$subscriber_id = add_noptin_subscriber( array(
'email' => '[email protected]',
'name' => 'Jane Doe',
'status' => 'subscribed',
'tags' => array( 'blog', 'customer' ),
'source' => 'api_import',
'ip_address' => $_SERVER['REMOTE_ADDR'],
'conversion_page' => 'https://example.com/thank-you',
'update_existing' => true, // Optional
) );
if ( is_numeric( $subscriber_id ) ) {
// Successfully added.
echo "Subscriber ID: " . $subscriber_id;
} else {
// Failed to add subscriber.
echo "Error: " . esc_html( $subscriber_id );
}
Behavior Details
- If the email already exists:
- Returns the subscriber ID without updating any data.
- If
update_existing
istrue
, the existing subscriber’s data is updated.
- Automatically generates a confirmation key and saves it.
- Sets tracking cookies unless disabled via filter:
noptin_disable_cookies
.
TIP:
This function will return a string if an error occurs. This usually happens if you pass an invalid email address.
For advanced usage, you can access the subscriber object using noptin_get_subscriber()
and inspect with $subscriber->get_data()
.
Leave a Reply