Home > Mobile >  How to pass php variable to html template from Database in WordPress
How to pass php variable to html template from Database in WordPress

Time:06-02

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:

<div >
    <p>Hello {$user_name}</p>
</div>

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

<php
 $user_name = "Bob";

 $template_query = 'select * from ' . $wpdb->get_blog_prefix();
 $template_query .= 'templates where id='.$some_id;
 $template_data = $wpdb->get_row( $template_query, ARRAY_A );
    
 $template = $template_data['template'];
 
 echo $template; 
 ?>

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.

CodePudding user response:

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.

  • Related