When working with themes or public-facing views for a website, WordPress components can generally be thought of in three distinct areas:

  1. Templates are used for rendering the view (that is, the markup and the styles) of data.
  2. Partials are reusable fragments of templates.
  3. Helper Functions are used to help process, format, and generally work with data.

As far as templates and partials are concerned, these are relatively common with themes or working with anything on the front-end, but we don’t see it as much as we do when talking about the context of the Dashboard.

But when it comes to working with the back-end, all of these things are still applicable. Sometimes you’ll see them in isolation – like with helper functions – other times, all three things can work together such as in the case of meta boxes.

That is, you have a function for defining the meta box, a function for rendering the meta box (which can include a template), and then the template may have multiple parts – or partials – such as the contents for various tabs.

The Spaghetti of WordPress Meta Box Code

In order to help keep templates and partials as clean as they can be, helper functions are useful in that they can wrap a lot of logic and abstract it into a single place so that we can call into it from the front-end.

Spaghetti Code

 

This keeps the front-end clean, helps keep business logic and/or domain logic separated into a single part in the project, and ultimately makes it easier to maintain code.

For example, let’s that that you have a meta box that displays three tabs:

And the content for each tab is contained in a partial:

One of the partials is responsible for taking a piece of meta data – say a string – and formatting it so that it looks like currency (for this example, USD) on the front-end. To do this, a function could be defined like this:

It grabs the meta data and if it exists, returns a formatted string; otherwise, returns an empty string. This leaves the partial code looking something like this:

Yes, there are a number of ways to format numbers for currency (the least of which is not money_format), but the code above is meant to highlight the separation of presentation and formatting logic – not which PHP function is best formatting money.

Anyway, this is much, much cleaner than a lot of the mixing of languages that we normally see in languages like this where multiple languages are contained in a single file. It creates a bit of spaghetti code, it mixes logic, presentation, style, and behavior which leaves us often asking “where is happening?”

Sure, there are some neat alternatives are seeking to solve this problem, but if you’re not interested in employing a new plugin, templating system, or whatever else, then using the basic nature of the built-in languages can go a long way.

Category:
Notes
Tags:

    Leave a Reply

    This site uses Akismet to reduce spam. Learn how your comment data is processed.