Writing a good WordPress template

I was asked to write a custom template for a wordpress based site, and I’m noticing that themes are usually one big unreadable mess of PHP code mixed with HTML, with a terrible indenting on top of it — even the default template follows this style.

What I’m doing now is put all the PHP code first, then the markup with minimum PHP just for control structures and variables — kind of what you’d do in a controller <-> view system, only in the same file.

Read More

What’s a good approach people use to write templates while keeping logic code separate from markup? It’s a moderately high traffic site, so I’d like to keep unnecessary overhead to a minimum.

Related posts

Leave a Reply

2 comments

  1. Try to use a WordPress Theme Framework instead of getting the default template and adapting it.

    I agree WordPress isn’t MVC, but you don’t need to mix up a lot of logic in your templates. Just use Template Tags accordingly and you can have really light themes without too much spaghetti code.

    When you realize that you’re mixing too much logic with presentation in your template files, encapsulate your logic into a function, move it to functions.php or create a plugin that you can call from your template and move on.

    Not strictly OO or MVC, but it’s maintainable.

  2. Its a little complicated to do this without core edits to WordPress itself. In the past I’ve used a class that acted as a controller that I would store all of my php code. This makes it a little simpler to separate your PHP code from that of the view. The problem with this approach is that any of the scripts that have its own class. Another option (more procedural) would be to have an actual file (I.E. footer.inc.php) that would be included at the top of the file and would then give you all of your variables.