Unlimited Plugins, WordPress themes, videos & courses! Unlimited asset downloads! From \$16.50/m

# How to Work With WordPress Comment Metadata

Difficulty:BeginnerLength:LongLanguages:
This post is part of a series called How to Work with WordPress Metadata.
How to Work With WordPress User Metadata

Throughout this series, we've looked at a number of the metadata APIs that are offered by WordPress. This includes the Post Meta API and the User Meta API. Today, we're going to be rounding out the series by looking at the WordPress Comment Meta API.

Note that this is that the final metadata API WordPress offers. As of WordPress 4.4, there's now a Term Metadata API. In order to fully understand it, it's important to understand taxonomies, terms, and their relationships within the context of WordPress. In an upcoming series, I'll be covering exactly that.

But today, we're going to be focused on managing metadata associated with comments. If you've not read anything else in this series up to this point, I recommend reviewing what we've covered thus far.

If you're all caught up, then let's get started.

## The WordPress Comment Meta API

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, we've said:

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.

## Working 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.

• 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 tutsplus-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.

As I've used throughout the previous articles, I'm using the following applications:

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_comments table 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.

### Updating Comment Meta

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.

### Retrieving Comment Meta

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.

#### Retrieving an Array

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.

#### Retrieving a Single Value

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:

Alternatively, if you know the data is unique, then the code will still look the same, as will the returned value.

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 Comment Meta

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.

#### Removing Unique Values

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:

Before running this code, the database should look something like this:

After you refresh the page, take a look at the database and you should see that the record has been removed and the database should look like this:

We'll talk a bit more about precautions to take when deleting data in the next section.

#### Removing Non-Unique Values

In other situations, let's say there are multiple values associated with a single meta key. We've seen this numerous times throughout this article. If you want to delete all of the records associated with a meta key, then you don't need to specify a meta value.

That is, if you just pass a comment ID and meta key to the delete_comment_meta function, it will remove all pieces of comment metadata. Write and execute the following code:

Refresh your page and then review the database. If there were no problems, your database should be clear of all records that previous had that 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.

## The Complete Source Code

As provided throughout this entire series, here's a copy of all of the source code that we've covered in this article. It's fully documented and includes comments not shown in some of the sections above.

Note that if you include this with the code from the rest of the articles in the series, you will need to be careful. Since everything is registered with the same hook, you may end up with weird results.

To combat this, I recommend one of the following two scenarios:

1. Create three separate files: one for each of the types of metadata APIs we've examined.
2. Comment the add_filter calls, except for the ones with which you're currently working.

Either of these will make it easier to work with all of the code we've covered thus far.

## Conclusion

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, remember all of my courses and tutorials are available on my profile page, and you can read more articles about WordPress and WordPress development on my blog

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. Whatever the case, you can see what all we have available in the Envato Marketplace.

Feel free to follow me on Twitter as well at @tommcfarlin, where I talk about various software development practices, many of which are relevant to web development and many of which are specifically geared towards WordPress.

As with all of my articles, please don't hesitate to leave any questions or comments in the feed below, and I'll aim to respond to each of them.