4elements, web design and consultancy

Throughout this series, we've focused on building maintainable WordPress meta boxes. By that, I mean that we've been working to create a WordPress plugin that's well-organized, follows WordPress coding standards, and that can be easily adapted and maintained as the project moves forward over time.

Though we've implemented some good practices, there is still room for refactoring. For this series, this is done by design. Whenever you're working on a project for a client or for a larger company, the odds of you having to maintain an existing codebase are rather high. As such, I wanted us to be able to return back to our codebase in order to refine some of the code that we've written.

Note this article will not be written in the format that the others have been written - that is, there won't be a "First we do this, then we do this" approach to development. Instead, we're going to highlight several areas in need of refactoring and then handle them independently of the other changes we're making.

Refactoring

Refactoring improves nonfunctional attributes of the software. Advantages include improved code readability and reduced complexity to improve source code maintainability, and create a more expressive internal architecture or object model to improve extensibility.

In short, it makes the code more readable, less complex, easier to follow, and does so all without changing the behavior of the code from the end-users standpoint.

This can be achieved a number of different ways each of which are unique to the given project. In our case, we're going to look at refactoring our constructors, some of our save methods, some of our helper methods, and more.

Ultimately, the goal is to show some strategies that can be used throughout your future WordPress endeavors. I'll aim to cover as much as possible in this article; however, note that there may be opportunities for additional refactoring that isn't covered.

If that's the case, great! Feel free to make them on your own instance of the codebase. With that said, let's get started.

Here, the main difference is that we've updated the version number that we're passing to the main class and we're also explicitly calling the initialize_hooks function within the context of run_author_commentary.

If you execute your code right now, everything should work exactly as it did prior to this refactoring.

I'd also like to add that you can make a case for having a separate class responsible for coordinating hooks and callbacks such that the responsibility resides in a separate class. Though I'm a fan of that approach, it's outside the scope of this particular article.

Next, let's go ahead and do the same thing to class-authors-commentary-meta-box.php. Rather than creating a new function, we can simply rename the constructor since the constructor doesn't really do anything. This means our code should go from looking like this:

Again, refresh the page and your plugin should still be functioning exactly as it were prior to this refactoring.

Helper Methods

In the Authors_Commentary_Meta_Box class, we have a number of conditionals in the save_post function that are very redundant. When this happens, this usually means that much of the functionality can be abstracted into a helper function and then called from within the function in which they were initially placed.

So let's take a look at each of these individually and work on refactoring this function.

1. The Initial Condition

The purpose of the first conditional check is to make sure that the current user has the ability to save data to the given post. Right now, we're literally checking to see if the current post type is a valid post type and if the user has permission to save given the current nonce values being passed by WordPress.

Right now, the code reads:

If this is not a valid post type or the user doesn't have permission to save, then exit this function.

It's not all together terrible, but could definitely be improved. Instead of having an OR, let's consolidate it into a single evaluation such that it reads:

If the user doesn't have permission to save, then exit this function.

Luckily, this is a relatively easy fix. Since the type of post that's being save helps to dictate whether or not the user has permission the save the post, we can move that logic into the user_can_save function.

So let's take the is_valid_post_type function and move it into the user_can_save function:

2. Checking The $_POST Array

Next up, before we begin sanitizing, validating, and saving (or deleting) the meta data, we're checking the $_POST collection to make sure that the data actually exists.

We can write a small helper function that will take care of this evaluation for us. Though we're essentially writing a little bit of code that makes our evaluation more verbose, the conditionals will read a bit clearer than if we'd just left them as-is.

First, introduce the following function (and note that it takes in a parameter):

At this point, we really only have one other aspect of this part of the code to refactor.

3. Sanitization and Saving

Right now, the way in which the post meta data is saved is done so through a process of evaluating the presence of the data in the $_POST collection, sanitizing it based on the type of information, and then saving it to the post meta data.

Ideally, we'd like to sanitize the data in its own function as well as save the post meta data in its own function. Thus, we need to introduce to new functions.

First, let's work on sanitization. Because we're dealing with textareas and arrays, there are a couple of ways in which we need to handle the sanitization call. Since we're either working with an array or we're not, we can create a function that accepts an optional parameter denoting whether or not we're working with an array.

If we are not working with an array, then we'll treat the incoming data as text; otherwise, we'll treat it as an array:

Next, we can update the sanitization calls to use this method. But before we do that, let's also write a small helper that will be responsible for updating the post meta data with the sanitized inputs:

Note that we could actually refactor this particular even more so there aren't as many conditionals, but for the sake of the length of the article, the length of time, and also trying to introduce some other strategies, this will be left up as an exercise to be done on your own time.

Conclusion

By now, we've completed our plugin. We've written a plugin that introduces a meta box for providing options for the authors who are writing blog posts.

Additionally, we've employed the WordPress coding standards, some strong file-organization strategies, and have created a number of helper methods and abstractions that will help us to maintain this particular plugin as it undergoes future development.

Because it's not easy to highlight every single opportunity for refactoring, there are likely additional changes that could be made. On your own time, feel free to try implementing some of them on your own.

Overall, I hope you've enjoyed the series and learned a lot from it, and I hope that it will help you to write better, more maintainable code in future WordPress-based projects.