Recently at work, there was a need to ask for additional data in the comments section of a WordPress site. A checkbox needed to be added to the comments form asking a question.

This sounded like a good use for WordPress comments meta data. There isn’t a lot of information out on the interwebs about how to use it, so I had to more or less figure this out…

So, what needed to be done was:

  • add a check box to the comments form
  • show in the WordPress comments admin whether or not the checkbox was selected
  • indicate in the comment notification email whether or not the checkbox was selected

Adding the checkbox to the comments form is the easiest part. To add the checkbox to the comments form open up your themes comments.php file and paste this into the area where you need it:

Now that the checkbox is in place, we need to make sure that the data (the checkbox value) is saved to the database. We also want that data to be visible when viewing the comments from within the WordPress admin. So, paste this in your theme’s functions.php file:

// allow the saving of comment meta data
function fpo_allow_show_comment ( $post_id ) {
$allow_show_comment = $_POST['publishc'];
if ( $allow_show_comment ) {
add_comment_meta( $post_id, 'publishc', $allow_show_comment, true );
}}
add_action( 'comment_post', 'fpo_allow_show_comment', 1 );

// display meta in the edit comments admin page
function show_commeta() {
if (is_admin()) {
   echo get_comment_text(), '

', get_comment_meta(get_comment_ID(), 'publishc',1), ''; }} add_action('comment_text', 'show_commeta');

The first function will allow comments meta data to be collected and to save it to the database. The second functions will show it in the comments admin pages.

Adding the comments meta data to the notification email proved to be the hardest to figure out – I couldn’t figure out a way to do it via plugin or editing functions.php. So, I decided to do this the least desirable way, which is to edit the WordPress core files, namely wp-includes/pluggable.php.

So find the function wp_notify_postauthor and look for the part that says if (‘comment’ == $comment_type) {. Paste these lines of code in whatever area of the notification email where you would like the comment meta to be included:

$notify_message .= __('Comment meta: ') ;
$notify_message .= sprintf( get_comment_meta($comment->comment_ID, 'publishc',1)) . "\r\n\r\n";

And that is that, hours and hours worth of trial and error. Hope you find it useful!

Test and works in WordPress versions 2.9 through 3.4.1.