admin管理员组

文章数量:1394189

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.

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.

Share Improve this question edited Jun 15, 2020 at 8:21 CommunityBot 1 asked Feb 6, 2020 at 11:31 Kevin NugentKevin Nugent 5631 gold badge8 silver badges20 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 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'],
    $content
);

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.

本文标签: Pass Variables or Variable PlaceHolder from Editor to PHP