最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Pass Variables or Variable Place-Holder from Editor to PHP

programmeradmin2浏览0评论

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.

发布评论

评论列表(0)

  1. 暂无评论