One of the things that I like about open source the most is having discussions not only about how a person goes about doing something, but why they’ve chosen a particular route over an alternative.
Yes, reading books, articles, and other material from prolific, well-known, and respected programmers matters – I’m definitely not saying that we should throw that out – but there’s a lot that can be learned from peers who are sitting a couple of tweets, emails, or gists away from you.
Though I generally enjoy seeing how other people have approached their work and understanding the rationale behind it, I’m also pretty open about how I approach certain problems if for no other reason that the garner feedback from those of you who take the time to update gists, add comments, and so on.
Add Multiple Meta Boxes in a Theme
Case in point: Just recently, I was asked how I go about creating multiple meta boxes when working in the context of
functions.php and a theme. In other words:
How do you approach creating multiple meta boxes outside of the object-oriented context?
In short, I usually follow these rules of thumb:
- Define a function that’s prefixed with the theme’s name and that is hooked to the `add_meta_boxes` action.
- Define a number of functions specifically for creating meta boxes and prefix them with `_`.
- Call each of the aforementioned functions in the first function that was written.
I’ll share some example code in just a moment, but I’ve found that the above approach helps to make sure that each meta box has its own function which makes it easy to label, pinpoint issues and to maintain.
This also ensures that each function is called in a single place so that if we want to, say, temporarily hide a meta box for the purposes of debugging, then we could just comment the function responsible for rendering the meta box.
For what it’s worth, it also allows use of the
_ function prefix which denotes that a function [that’s defined outside the scope of a class] is private.
What Does This Look Like?
Here, code often speaks better than words do so here’s a really small example showing how I typically go about doing this:
If you’ve read the above rules of thumb, then nothing in the above gist should be all of that surprising. After all, it’s really nothing more than just a codified version of the points I made above.
In my opinion, the most important thing to take away is that each meta box has its own function (and own set of functions) for displaying its information. Keeping all of that code in a single function becomes a code smell and can become increasingly harder to maintain as a project grows.
With that said, I’m obviously open to suggestions and recommendations based and your own experience.