Programmatically Adding Comment Metadata from JavaScript


  • JavaScript side: Add hidden input fields named myplugin_comment_meta['foo'] to the commentform element. Example.
  • PHP side: Add preprocess_comment filter callback and add $_POST['myplugin_comment_meta'] array items to the comment_meta array in the returned value. Example.

I’m writing a WordPress plugin that analyzes toxic comments and encourages the author to be kind instead, and I want to log the toxicity scores from the API as metadata on the comment. That’s easy to do on the PHP side, but it’s not as clear for a client-side app.

You can’t make a REST API request, because your script will never know the ID of the comment, since the form isn’t submitted via REST or AJAX. Even if you did know the ID, it’d be inelegant to send a second request instead of just including the meta data in the same form submission that creates the comment.

We can get half-way to a solution by injecting hidden input fields into the form container, so that the data gets submitted when the comment is created. For an example, see front-end/main/controller.js.

That’s almost all that it takes, since wp_insert_comment() automatically creates meta values that are passed to it. Unfortunately, though, wp_handle_comment_submission() doesn’t recognize comment meta fields, and strips them out of the data that gets passed to wp_insert_comment().

So in order to bridge that gap, you need to have a preprocess_comment callback on the PHP side to add the meta values into the array of data that gets passed to wp_insert_comment(). Once the data is there, though, that function will take care of actually saving it to the corresponding comment; you don’t need to ever manually call add_comment_meta(). For an example, see compassionate-comments.php.

As always, it’s important to keep security in mind. Since the data is coming from the client side, it can’t be trusted, and needs to be properly validated and sanitized.

It’s also a good idea to use a prefixed name for the input fields, instead of just comment_meta, for future proofing against #47447.

Leave a Reply

Your email address will not be published. Required fields are marked *