WP Plugin Templating

WordPress is great but sometimes there are aspects of the design that really irritate me. One of these annoyances is the extremely common but widely accepted practice of putting HTML markup inside the PHP methods/functions of the plugin itself.

Of course programmers can hardly be blamed for this as it is an extremely common, and widely accepted, practice but a lesson or two learned from Zend Framework (for example) can come in handy. The aim of the exercise is to maintain a degree of separation between the model and the view in the MVC style. MVC isn’t perfect but it does work, generally, and contains a great deal that encourages for good programming practice.

There are several ways of implementing templating for WordPress plugins and I’ll present one here. It’s pretty simple to use but easy to build on. We’re not tinkering with deep WordPress here but aiming to point at good practice

Here’s a simple example of a function that outputs some text.

 Essentially what happens is that the entire function, when called, will print the HTML content immediately.

Here is another way of doing it. 

In this example the template is maintained separately and the showPanel() function returns a string built whilst buffering the output from the included file.

 

¬†That’s all there is to it really. I like this approach because of the clarity it brings.

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *