7

I have some PHP experience, but hardly any WP theme writing experience...I'm just starting the journey.

All of the themes I have looked at so far in the .org repository have code that looks like this:

<?php if (condition) { ?>
..some html
<?php } else { ?>
..some other html
<?php } ?>

instead of:

<?php
if (condition) {
  echo ..some html
}
else {
  echo ..some other html
}
?>

I can see that when using an editor like notepad++ we'd rather have the html "naked" and not in an echo statement, to give the editor the ability to color-code and match up HTML tags with their ending tags, etc.

But I see a lot of templates that have a TON of PHP code and very little HTML -- and they still wrap PHP tags around every line of code. To me, that makes it hard to read.

Is there a technical reason for that, or just a preference on the part of the developer?

2
  • 3
    Good question - how about people might not really understand what they are doing?
    – SimonT
    Commented Nov 12, 2015 at 23:08
  • This is why on jobs sites there are offers like "WordPress Developer" and "PHP Developer", second one being from companies that want good quality, first one from companies that would not pay a fair wage and don't care what's in the code as long as "they deliver in time"... Sorry if somebody would be offended, but it's the cruel truth. Commented Nov 18, 2015 at 8:19

2 Answers 2

7

As always, people copy paste whatever they learned from and IIRC the first style is the coding style of wordpress core.

As you said yourself, when there is a big block of generated HTML it is easier to look at (and balance tags) under the first style, but pragmatic people will use the second whenever that is not the case.

It is really just coding style preference nothing technical behind it.

0
1

Although you may argue that the code is harder to read when you go into and out of PHP mode more often, it is also good and widely-recommended practice in PHP not to mix output styles.

That is, either you output HTML from HTML mode, or you output HTML from echo statements … but you don't mix styles. That would create a maintenance nightmare.

The authors of the templates you're reading are following that best practice.

However, ultimately, yes, this is a style/management issue only: nothing in the language inherently requires it.

A sensible templating system would not allow inline PHP at all, instead allowing only declarative extensions to the HTML markup, but that's another story…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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