Cybercampbell
Cybercampbell

Reputation: 2606

PHP replace token in html email variable before sending

I have an email that I send out to subscribers of my site. I do this by getting the subscriber list from my database and the looping through the array and sending one email at a time... I know there is a way to send all at once but this is why I do it this way and the bit I need help with...

The HTML email contains 2 tokens:

{name} and {date}

What i need to do is insert the date in the HTML email replacing the {date} token and insert the name replacing the {name} for each email send (as the name is always different).

This is what I have:

        $result = $wpdb->get_results( "SELECT * FROM wp_newsletter WHERE `id` IN ( $userIds )");
        for($i = 0, $size = sizeof($result); $i < $size; ++$i){
          add_filter('wp_mail_content_type',create_function('', 'return "text/html";'));
          $to .= $result[$i]->name.'<'.$result[$i]->email.'>';
          $mail = wp_mail( $to, $subject , $message, $headers);
        }

as you can see above I have two variables from the database:

$result[$i]->name

$result[$i]->email

and $message is the HTML email body that has the 2 tokens that needs to be replaced.

so.... everything is working as expected for the looping and sending I just need some help with how I do the token replace for {name} and {date}.

Any help with this will be very much appreciated.

Upvotes: 3

Views: 2646

Answers (2)

silentw
silentw

Reputation: 4885

$message = str_replace('{name}',$result[$i]->name,$message);
$message = str_replace('{date}',date('Y/m/d H:i:s'),$message);

str_replace('{name}',$result[$i]->name);
str_replace('{date}',date('Y/m/d H:i:s'));

Upvotes: 1

Madbreaks
Madbreaks

Reputation: 19549

This is easily done with PHP's str_replace function, docs here.

...
$message = str_replace('{name}', $result[$i]->name, $message);
$message = str_replace('{date}', date('Y/m/d H:i:s'), $message);  // Or your preferred date format

$mail = wp_mail( $to, $subject , $message, $headers);

Note that if you know there will only be a single instance of {name} and/or {date} you can pass a 4th parameter $count to str_replace and it will quit after replacing the first match.

Cheers

Upvotes: 2

Related Questions