Advertisement
  1. Code
  2. WordPress
Code

Creating Maintainable WordPress Meta Boxes: Verify and Sanitize

by
Difficulty:BeginnerLength:LongLanguages:
This post is part of a series called Creating Maintainable WordPress Meta Boxes.
Creating Maintainable WordPress Meta Boxes: Finish The Front-End
Creating Maintainable WordPress Meta Boxes: Save and Retrieve

Throughout this series, we've been creating a plugin that's meant to provide authors with a way to collect, manage, and save ideas and references to content that they're creating within WordPress.

While doing so, we're also looking at ways that we can organize our plugin so that the code and the file organization is clear and maintainable so that as the plugin continues development, we're able to easily add, remove, and maintain its features.

Up to this point, we've put together the basic file organization of the plugin as well as the front-end, but we haven't actually implemented functionality for saving information to the database. And if you can't save information, then the plugin is of little benefit to anyone.

In this post, we're going to hop back into the server-side code and begin implementing the functionality that will:

  1. Verify the user has the ability to save post meta data
  2. Sanitize the post meta data
  3. Save the post meta data
  4. Validate and retrieve the post meta data

We've got our work cut out for us. In this article, we're going to be looking at the first two steps and then in the next post, we'll be looking at the final two steps.

Verifying Permissions

In order to verify that the user has the ability to publish to save post meta data, we need to implement a security check during the serialization process. In order to do this, we need to take advantage of a nonce value.

A nonce is a "number used once" to protect URLs and forms from being misused.

1. Add a Nonce

In order to introduce one into our meta box, we can implement the functionality in the markup that's responsible for rendering the post template. To do this, load admin/views/authors-commentary-navigation.php and update the template so that it includes a call to wp_nonce_field:

In the code above, we've introduced a nonce that corresponds to the action of saving the author's commentary (which we've named authors_commentary_nonce) and associated it with a value that's identified by authors_commentary.

We'll see where this comes into play momentarily. For now, if you load your browser, you won't see anything new display. That's because the nonce values are displayed in a hidden field. 

For those who are curious, you can launch your favorite browser's development tools, inspect the meta box, and you should find something like the following in the markup:

Of course, the value of your nonce will be different.

2. Check the Nonce

In order to make sure the user has permission to save the post, we want to check three things:

  1. that the user is saving information for a post post type
  2. that the post is not being automatically saved by WordPress
  3. that the user actually has permission to save

We'll write two helper functions to achieve the first and third, and we'll use some built-in functions to check number two (which will actually be used in the second helper function).

First, let's go ahead and setup the hook and the function that will be used to leverage the helper functions and save the meta data. In the constructor for Authors_Commentary_Meta_Box, add the following line of code:

Next, let's define the function. Note that I'm making calls to two functions in the following block of code. We'll be defining them momentarily:

Given the code above, we're telling WordPress to fire our save_post function whenever its save_post action is called. Inside of the function, we're saying "If the post that's being saved is not a 'post' post type, or if the user does not have permission to save, then exit the function."

Of course, we need to define the functions so that the logic works. First, we'll write the is_valid_post_type function as a private function of the current class. It will check the $_POST array to ensure that the type of post that's being saved is, in fact, a post.

Next, we'll add the user_can_save function. This is the function that will ensure that the post isn't being saved by WordPress, and that if a user is saving the function, then the nonce value associated with the post action is properly set.

Notice here that we're passing in the nonce_action and the nonce_id that we defined in the template in the first step. We're also using wp_verify_nonce in conjunction with said information.

This is how we can verify that the post that's being saved is done so by a user that has the proper access and permissions.

Sanitize the Data

Assuming that the user is working with a standard post type and that the s/he has permission to save information, we need to sanitize the data.

To do this, we need to do this following:

  1. Check to make sure that none of the information in the post meta data is empty
  2. Strip our anything that could be dangerous to write to the database

After we do this, then we'll look at saving the information for each of the meta boxes. But first, let's work on sanitization. There are a couple of ways that we can go about implementing this. For the purposes of this post, we'll do it in the most straightforward way possible: We'll check for the existence of the information based on its key, then, if it exists, we'll sanitize it.

For experienced programmers, you're likely going to notice some code smells with the code we're about to write. Later in this series, we'll be doing some refactoring to see how we can make the plugin more maintainable so it's all part of the intention of this particular post.

With that said, hop back into the save_post function.

1. Drafts

Since the first tab that exists within the meta box is the Drafts tab, we'll start with it. Notice that it's a textarea, so the logic that exists for sanitizing that information should be as follows:

  • remove any HTML tags
  • escape the contents of the text area

Recall that the textarea is named authors-commentary-drafts so that we can access it within the $_POST array. To achieve this, we'll use the following code:

Simply put, we're checking to see if the information in the $_POST array is empty. If not, then we'll sanitize the data.

2. Resources

This particular field is a little more form because it's dynamic. That is, the user can have anything from zero-to-many input fields all of which we'll need to manage. Remember that this particular tab is designed to primarily be for URLs so we need to make sure that we're safely sanitizing the information in that way.

First, we need to make one small change to the createInputElement function that exists within the admin/assets/js/resources.js file. Specifically, we need to make sure that the name attribute is using an array so that we can properly access it and iterate through it when looking at $_POST data.

Make sure that the lines of code responsible for creating the actual element looks like this:

Notice that the key to what we've done lies in the line that updates the name. Specifically, we're placing the number of inputs an indexes of the array.

Next, hop back into the save_post function and add the following code (which we'll discuss after the block):

Because we're working with an array of inputs, we need to first check that the array isn't empty. If it's not, then we need to iterate through it because we aren't sure how many inputs we're going to have to manage.

Similar to the previous block, we're doing a basic level of sanitization and escaping. This is something that you can make as aggressive or as relaxed as you'd like. We'll be coming back to this conditional in the next post when it's time to save the data.

3. Published

This tab is similar to the previous tabs in that we're dealing with an indeterminate number of elements that we need to sanitize. This means that we're going to need to make a small update to the partial responsible for rendering this input.

On the upside, we're only dealing with a checkbox which has a boolean value of being checked or not (or, specifically, 'on' or empty) so sanitizing the information is really easy.

First, let's update the partial. Locate admin/views/partials/published.php. Next, find the line that defines the input checkbox and change it so that it looks like this:

Notice that we've changed the name attribute so that it uses a an array with an index as its value. Next, we'll hop back into the save_post function one more time in order to introduce validation on this particular element:

Just as we've done with the previous pieces of data, we first check to see if the content exists. If so, then we sanitize it to prepare it for saving. If it doesn't then we don't do anything.

On To Saving

At this point, we're positioned to take on the last two points of the series:

  1. Saving and Retrieving
  2. Refactoring

Starting in the next post, we'll revisit the code that we've written in this post to see how we can save it to the database and retrieve it from the database in order to display it on the front-end.

Next, we'll move on to refactoring. After all, part of writing maintainable code is making sure that it's well-organized and easily changeable. Since the code that we work with on a day-to-day basis has already been written and could stand to be refactored, we're going to see how to do that by the end of the series.

In the meantime, review the code above, check out the source from GitHub, and leave any questions and comments in the field below. 

Advertisement
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.