Work with WordPress comment metadata

Work with WordPress comment metadata

Online by J&S Code
11 July 2017 | PHP WP snippets, code & hacks | 231 recognitions

Throughout this series, we’ve been using the WordPress definition of metadata as our foundation for understanding how this information is represented in the context of our environment.

Specifically, codex:

Meta-data is handled with key/value pairs. The key is the name of the meta-data element. The value is the information that will appear in the meta-data list on each individual post that the information is associated with.

In keeping consistent with the rest of the content that we’ve seen throughout this series, this definition holds true with comment metadata just as it did with post metadata and user metadata.

The upside to this is that once you’ve gotten a handle on the various metadata APIs that we’ve covered, there should be very little surprise with how other metadata functionality works. There may be a few things different depending on which API you’re using, but the gist of the functionality will be the same.

And, as you will see, this continues to be the case with the comment metadata API.

As with the other APIs we’ve examined throughout this series, there are four primary functions that we’re going to explore:

  • add_comment_meta
  • update_comment_meta
  • get_comment_meta
  • delete_comment_meta

By now, you likely know what to expect when it comes to, say, the differences between adding comment metadata and updating comment metadata. Or, say, working with deleting comment metadata.

That doesn’t change the fact that it’s worth exploring each of these API functions in detail to make sure we’ve covered all there is to know when working with them.

For the rest of this article, I’m assuming the following:

  • You’re running a local development environment with a web server, database server, and PHP.
  • You have a copy of WordPress installed.
  • You have a copy of js-metadata.php set up in your theme’s directory, and it’s included in your theme’s functions.php file.
  • You have your IDE and database front-end of choice readily available.

Finally, all of the metadata with which we’ll be working is stored in the wp_commentmeta database table, so all of the screenshots that you see of the database will be of that particular table.

Unlike some of the other metadata tables that we’ve seen, the wp_commentmeta table starts off empty (assuming you’re working with a relatively fresh version of WordPress).

This is good as it will give us a clean slate, of sorts, to use when examining the various API functions. Note that for all of the examples below, we’re going to make sure all of this happens on the Hello World! post. This post has the ID of 1. If you want to use another page, simply replace 1 with the ID of the post in question.

With all of that in place, let’s start looking at what’s available.

In order to get started adding metadata to our comments, it’s important to take a look at the wp_commentstable to see what comments already exist. If you’re working with a fresh installation of WordPress, then you’ll likely see a single record:

This is the default comment that ships with WordPress, and it will do fine for the examples we’ll be using.

If, on the other hand, you’re working with a database full of comments, no problem! All you need to know is what comment you’re working with (via its ID), and make sure you’re consistent with the code we use below.

As with other APIs we’ve reviewed in this series, adding metadata to comments comes in two forms: unique and non-unique. We’re going to review both.

The add_comment_meta function accepts three parameters and an optional fourth parameter. If you pass true as the fourth parameter, then the metadata will only be added if the specified meta key doesn’t exist.

Make sense? Let’s take a look. First, we’ll set up a function that will add some metadata associated with the first comment (but will only do so on the post having the ID of 1):

Notice that I’ve passed the true parameter. So each time I refresh the page, WordPress will see that I want this value to be unique so it will not add any more information to the database table associated with that meta key.

If, on the other hand, I want to associate multiple values with the same meta key, I would remove the true parameter. For example, use the following code:

And then refresh the page, say, three times. If all goes as expected, you can see three new records, each of which contains a random number as generated by the call to rand() in the meta value argument. It’s easy enough to keep straight, right? If you want a single value associated with a single key, then pass true as the optional fourth argument; otherwise, don’t specify anything.

If you want to update existing comment metadata, then it’s important to know the comment ID, the meta key, and the meta value. This means that WordPress will look at the specified meta key and associate it with the specified meta value.

If the meta value exists, then it will be overwritten. If the meta value does not exist, then it will be created. Notice in that last sentence that there’s a bit of functionality that you can use when adding metadata: If you want to have a unique piece of information written to the metadata table, then you can use update_comment_meta and it will write it as a unique value.

This may result in a bit of confusing code (since it reads as if it’s updating something that doesn’t exist), but it also allows you to enforce that only a single record will exist for the given meta key.

What happens when there is a meta key associated with several meta values? In that case, you need to know the value that you’re looking to replace. In some instances, you may know exactly what this is. In other instances, you may need to retrieve the information to find it (which we’ll cover in the next section).

Assuming that we want to update one of the records we’ve created, such as one of the random numbers we saw in the example above, we can look it up using the database front-end and specify it as the previous value in the following code:

After that, we can refresh the page, take a look in our database, and see the change. Note that the work we just did is relevant to a development environment and is not the way in which you would go about handling this in production.

Instead, you may need to run a query or retrieve a set of values before updating them. This leads us into the next topic.

Whenever you’re retrieving comment metadata, you need to decide if you want to retrieve a single value or all of the values associated with the specified meta key.

Perhaps another way of looking at this is as follows: If multiple pieces of metadata have been added with the same meta key (which we covered in the Adding Unique Metadata section above), then you will likely want to retrieve the entire collection of records.

If, on the other hand, you only want to retrieve one record because you know it’s unique or because it was created with the update_comment_meta function, then you want WordPress to return it to you in a single value.

The get_comment_meta function requires three arguments and an optional fourth depending on what you want to retrieve.

Let’s say that you’re looking to retrieve a collection of all values associated with a single meta key. To do this, you would make a call to get_comment_meta and you’d specify the comment ID and the meta key.

In the code above, we’re printing it out to the web browser, but you would be able to work with this data in any way you’d like once you’ve retrieved it. The most important thing to notice, though, is that the value is returned as an array.

If you want to retrieve a single value, then you only need to specify the comment ID and the meta key in the get_comment_meta function. If you happen to be dealing with a meta key with multiple values, then the first value that was created is what will be returned.

For example, let’s say there are three records associated with one meta key, and you only want to retrieve one value. Your code will look like this:

And the resulting value will look something like this:

The only difference is that the first example was retrieved from a set of multiple records, and the second example was retrieved from a single record. Also note that if you’re dealing with a unique value, then it will still be returned to you as an array, but a single index array.

This is important to note because if you plan on doing any type of comparison, especially to a value of a different type, such as an integer, then you will need to grab the value from the array, and you will likely want to do type conversion before making a comparison.

Deleting metadata is a straightforward operation: It requires the comment ID, a meta key, and an optional meta value.

If you don’t specify the meta value, then all records associated with the meta key will be removed. If, however, you specify the meta value, then only that single record will be removed.

For the purpose of this example, assume that we know a single piece of metadata exists for a given meta key. This means that the meta key must be unique for each user, so perhaps it uses something like a uniquely generated ID, a time stamp, or something similar.

To remove a unique value, we simply pass the comment ID and the meta key:

But remember that removing data from a database can be dangerous, especially if you accidentally delete something that you never meant to delete. To that end, it’s important to keep backups of your database in production environments so that you can always restore it if something goes wrong.

Further, this demonstrates why it’s so important to have a local development environment and a staging environment for testing before deploying the code to a production environment.

Whether you’re working with a metadata API or one of the other APIs, each WordPress developer should always have quick access to the WordPress Codex for quickly researching what APIs are available and how they should be used.

As we’ve worked through this series, you should see how the API designed around metadata is consistent. This makes for an easy-to-use, powerful API for extending some of the core WordPress functionality.

Additionally, I’ve mentioned that there’s another metadata API that was introduced in WordPress 4.4. I plan to cover that in an upcoming series, but it will require an examination of some of the other functionality that’s based on it.

For now, we’ve covered plenty of material to help you level up your existing WordPress skills. Until the next article you can read more articles about WordPress and WordPress development.

WordPress has an active economy. There are themes, plugins, libraries, and many other products that help you build out your site and project. The open source nature of the platform also makes it a great option from which you can better your programming skills.

About The Author

J&S Code

Sorin C is an entrepreneur, online marketer, and an employee of an IT company. When not building websites, creating content, or helping customers improve their online business, spend time with their wife and two beautiful children. Although he still feels new in WordPress, he enjoys sharing what he has learned with all of you! If you want to get in touch with him, you can do this through this website.

Put here your thoughts

Your email address will not be published. Please complete all fields * correctly You may use these HTML tags: bold text, italicised text, and paragraphs.

On the same idea

How to Remove HTML Tags from WordPress Comments
Online by stevenmedia | 8 November 2017

Nowadays, a lot of bloggers choose to remove HTML tag from WordPress websites. However, for beginners and newbies in this field, they may feel confused about the practice. Meanwhile, some...

How to create a WordPress child theme
Online by stevenmedia | 1 October 2017

The WordPress platform is a magnet for those who want to take matters into their own hands, who want complete control over their websites and want to be independent in...

Useful WordPress Hook hacks
Online by stevenmedia | 30 September 2017

Hooks are very useful in WordPress. They allow you to “hook” a custom function to an existing function, which allows you to modify WordPress’ functionality without editing core files. In...