Skip to content
Advertisement

How to pass php variable to html template from Database in WordPress

I’m making my own WP plugin, which has a text field containing some template, which I save to the database (table=templates, field=template), something like this:

JavaScript

Then I’m trying to show a message to a user:

JavaScript

And it is output “Hello {$user_name}” instead of “Hello Bob”

I can not get how to pass PHP variables to HTML throw the database.

I’ll be thankful for any help.

Advertisement

Answer

From the DB $template will contain just a plain text string, not PHP. You will have to replace the placeholder {$user_name} in $template with the value in $user_name through PHP.

E.g.:

Instead of

echo $template;

Try:

echo str_replace('{$user_name}', $user_name, $template);

which will output:

Hello Bob

Also note that the ? is missing from your opening <?php tag.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement