Tech TipsWordPress

Change Empty Subscriber Names With a Default Value

By November 20, 2017 No Comments

You may find yourself having a list of subscriber where few of them have not the first name. When you send personalized newsletter starting with “Dear {name},” you end up in sending emails starting as “Dear,”. It is not bad at all (note that Newsletter removes the space before the {name} tag when it is empty).

Maybe you prefer to act differently, forcing the name to a default value, for example changing it to “customer” to have a resulting salutation “Dear customer,”.

You can do that with few line of code that can be added to the functions.php file of you theme. Here the code:

add_filter(‘newsletter_replace_name’, ‘my_newsletter_replace_name’, 10, 2);

function my_newsletter_replace_name($name, $user) {
if (empty($name)) return ‘customer’;
return $name;
}

you can move forward and make things a little more complicated. Why not extract a “name” from the email address (if the name is missing)? Here the code:

add_filter('newsletter_replace_name', 'my_newsletter_replace_name', 10, 2);

function my_newsletter_replace_name($name, $user) {
 if (!empty($name)) return $name;
 
 // Build a name from the email address
 list($alternative) = explode('@', $user->email);
 
 // Remove dots, dash, underscores, ...
 $alternative = preg_replace('/[^a-z0-9]/i', ' ', $alternative);
 
 // Uppercase first letter of each word
 $alternative = ucwords($alternative);
 
 return $alternative;
}

Those examples are only starting point, you can extend them to any level and to cover every your need. To test your code, you can use the “test” button while composing a newsletter, just be sure you added the {name} tag on it.

Note: the {name} tag works even on your subjects, so be sure your replacements are ok even when they appears on newsletter subjects. Hence, DO NOT use HTML!