Using WordPress ‘add_comment_meta()’ PHP function

The add_comment_meta() WordPress PHP function is used to add a meta data field to a comment in your WordPress site.


Let’s say you have a comment with the ID of 123, and you want to add a meta field named “rating” with the value of 5. The code would look like this:

add_comment_meta(123, 'rating', 5);


  • $comment_id (int) Required – The ID of the comment to which you want to add the meta field.
  • $meta_key (string) Required – The name of the meta field you want to add.
  • $meta_value (mixed) Required – The value for the meta field. This must be serializable if non-scalar.
  • $unique (bool) Optional – This determines whether the same key should not be added. Default is false.

More information

See WordPress Developer Resources: add_comment_meta()


Adding a Basic Meta Field

Let’s add a basic meta field named ‘rating’ to a comment with the ID of 123. The meta field’s value will be 5.

add_comment_meta(123, 'rating', 5);

Adding a Meta Field Only If It’s Unique

If you want to ensure that the ‘rating’ field is unique and is not added if it already exists, you can set the $unique parameter to true.

add_comment_meta(123, 'rating', 5, true);

Adding a Serialized Array as Meta Value

If the meta value is an array, it will be serialized automatically. Here, we’re adding an array of ‘tags’ to the comment.

add_comment_meta(123, 'tags', array('tag1', 'tag2', 'tag3'));

Adding Meta Field to a New Comment

You can use the ‘comment_post’ action to automatically add a meta field to every new comment. Here, we’re adding a ‘status’ field with the value ‘unread’ to every new comment.

function add_status_comment_field( $comment_id ) {
    add_comment_meta($comment_id, 'status', 'unread');
add_action('comment_post', 'add_status_comment_field');

Adding User Input as Meta Field

If you want to store user input as a meta field, you can get the input from $_POST. Let’s say you have a custom form field ‘user_location’ that you want to store.

function add_location_comment_field( $comment_id ) {
    if (isset($_POST['user_location'])) {
        add_comment_meta($comment_id, 'user_location', $_POST['user_location']);
add_action('comment_post', 'add_location_comment_field');