WordPress now features a function to allow you to store meta data for each comment. Just like it’s able to do so for posts. It seems that, under the hood, WordPress has functionality that potentially prepares it for metadata on whatever you want. As get_comment_meta is nothing but a call to update_meta with the first parameter prefilled with ‘comment’.
Anyway, when you are reading this you are probably looking for a way to get get_comment_meta working. It’s not documented in the Codex (yet) and other information on the web is not always easy to understand or complete. So here’s my try to make you understand get_comment_meta and with it comes update_comment_meta.
- update_comment_meta -> will allow us to update a comment meta entry and is also used to create a meta entry
- get_comment_meta -> will alows us to retreive the meta entry for each comment
The metadata for the comments is stored in the database in its own table and the comment ID is required to link the comment to its metadata.
To add comment metadata, a simple call to it like this will make it work:
update_comment_meta($comment_id, 'key', 'value');
If you save the data when someone is adding a new comment, you would probably receive the $comment_id from a call to e.g. wp_new_comment.
Retrieving the comment metadata is a little different than expected, it has a small (and simple) twist. The trick is in the third parameter here:
get_comment_meta($comment_id, 'key', true);
This will return a single result (e.g. string) while the following will result in returing an array:
It’s as simple as this! In case you want the comment ID while retrieving comments, you can replace $comment_id with get_comment_ID();