The whole point of this entire series has been to demonstrate how to logically separate the various pieces that go into components a project by breaking them down into related components. Though I’ve been using them as a means to an end, the purpose of all of this is not about how to use WordPress meta boxes.
Anyway, to round out the series, the last thing to do is to take a look at exactly how to leverage the work that we’ve done thus far to bringing it to the front end so that the code that works on the backend actually does something on the front.
It’s not going to be anything particularly special or unique, but it should showcase the point nonetheless.
WordPress Meta Boxes: Bringing It to the Front End
By now, several key points have been hit:
- Aiming for Simplicity (through the use of Meta Boxes),
- The separation of concerns of business logic and presentation logic,
- Understanding each component that goes into something as simple as a meta box.
At this point, the last thing that needs to be done is to actually read the meta data value that been saved, and toggle the front end appropriately.
Given the fact that the option that’s built into the meta box reads:
Hide the content from displaying on this post?
It’s pretty clear in seeing what’s going to be done, right?
Hiding the Content
To do this, we only need to do the following:
- Define a function that hooks into `the_content` action.
- If the meta box option is checked, replace the content with a message.
- If the meta box option is not checked, display the post as usual.
To do this, we need to add a single function to
functions.php. This requires only a little bit of code. See the following gist:
Nothing too complicated.
Obviously this could be improved and the functionality could extend to, say, logged in users or users of a certain role; however, what’s above is enough to demonstrate how to read the values that we’ve been working on throughout the rest of the series and put them to use.
Driving the Point Home
As I’ve said multiple times, the point of this entire series is not about how to work with WordPress meta boxes, but it’s how to approach WordPress development using a mindset that gives us a more flexible and maintainable code base over time.
Rather that lumping everything together in god-classes or in monolithic
functions.php files, we can separate the responsibilities of our code through the use of slightly more organized means.
Sure, it takes a little bit of extra time, but I’d argue that the time spent from the outset can save time later in the project because there’s a single place for each area of responsibility that we’d need to turn to whenever changes need to be made.
Finally, this isn’t the way to do it but a way to do it. Others will have recommendations that are likely better, but hopefully this gives a little bit more insight on how to achieve a little more simplicity with the work you do with WordPress in your current and future work.