I'm building a method for my client to construct a message content to be sent with wp_mail. Within that I'd like them to be able to choose variables, for example the message might look like this in my admin custom field:

Email: $email_address$

First Name: $first_name$

So that when I iterate over the lines I can spot a variable place-holder and replace $email_address$ with my variable so my PHP would look like:

$body = 'Email Address: [email protected]<br>First Name: Mickey Mouse';
wp_mail( $to, $subject, $body, $headers );

I suppose I'm wondering if there's a particular or PHP-ish way to do this, I'm sure I've seen it in plugins before but don't recall the exact formatting.

1 Answer 1


You should use str_replace, which accepts arrays as arguments:

$content = "Email: {{email}}\nFirst Name: {{first_name}}";
$body = str_replace(
    ['{{email}}', '{{first_name}}'],
    ['[email protected]', 'Mickey Mouse'],

Be careful about using $ in your placeholders. Since it's widely used in PHP, it's not safe. It was the reason I've used mustache-like syntax in my example.

  • Nice. Thanks, @Cadu. I'll give that a shot. Feb 6, 2020 at 12:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.