Tell me more ×
WordPress Answers is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I'm creating a custom plugin which needs to display HTML with dynamically updated values.

To illustrate, here's what I want to achieve:

<h1><?php print $title; ?></h1>
<h3><?php print $subtitle; ?></h3>
<div class="description"><?php print $content; ?></div>

How can I define a template, pass some variables and get output in return from my custom plugin? I do not want to embed everything as a variable name as it's messy; going back between PHP and HTML in a middle of a function doesn't seem any cleaner either.

What is WP way of doing this?

Thanks!

share|improve this question

1 Answer

up vote 1 down vote accepted

The various styles of mixing and matching HTML and PHP has always been a bear. Circumstances sometimes dictate the method you use, but many developers prefer one style or another and WordPress tends to use the style in your example.

Another option, which is a bit cleaner in my opinion is to make use of the heredoc syntax in PHP which allows for simple variable substitution. http://php.net/manual/en/language.types.string.php

$Output = <<< EOF
<h1>$title</h1>
<h3>$subtitle</h3>
<div class="description">$content</div>
EOF;

return $Output;

You can't do away with the PHP variables entirely, but you can make it easier to write, read, and maintain.

share|improve this answer
Thank you for your response. I also have seen some plugins simply including the so-called view file which just uses variables defined earlier in the function. That one seems the cleanest of all, even though still feels hackish. Is that recommended to be used? – Ivanhoe123 Nov 6 '12 at 20:09
I'm not aware of WordPress actually stating a preference, but as I said the whole WordPress community of developers tends to use the inline style that you have as an example. Just keep in mind that the heredoc style does have it's limits and won't work all of the time. – Stephen Nov 6 '12 at 20:13
Thank you for your answer :) – Ivanhoe123 Nov 6 '12 at 20:26

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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