Add Custom Fields to the WordPress Comment Form with Comment Meta

Add a rating field to the WordPress comment form with comment meta

Comments have their own meta table, which works like post meta: add_comment_meta(), update_comment_meta(), get_comment_meta(). With it the comment form can collect more than a name, an email and a text: a rating, an RSVP answer, a topic. WooCommerce product reviews are built exactly this way. Three steps are needed: the field in the form, saving it, and showing it.

Problem: Readers should rate a post from 1 to 5 stars when they comment, and the post should show the average rating.

Solution: Add the field with the comment_form_fields filter, validate it on preprocess_comment, save it with update_comment_meta() on comment_post, show it with the comment_text filter, and calculate the average from the approved comments.

The field

<?php
add_filter( 'comment_form_fields', 'ha_comment_rating_field' );

function ha_comment_rating_field( $fields ) {
    if ( ! is_singular( 'post' ) ) {
        return $fields;
    }

    $html = '<fieldset class="comment-form-rating"><legend>' . esc_html__( 'Your rating', 'textdomain' ) . '</legend>';

    for ( $i = 5; $i >= 1; $i-- ) {
        $html .= sprintf(
            '<label><input type="radio" name="ha_rating" value="%1$d" required> %2$s</label> ',
            $i,
            esc_html( sprintf( _n( '%d star', '%d stars', $i, 'textdomain' ), $i ) )
        );
    }

    $fields['ha_rating'] = $html . '</fieldset>';

    return $fields;
}

The filter returns all fields of the form (comment, name, email, URL) in the order they are printed; a new key at the end puts the rating after them.

Validation and saving

<?php
// Refuse comments on posts without a valid rating
add_filter( 'preprocess_comment', function ( $commentdata ) {
    $post_type = get_post_type( $commentdata['comment_post_ID'] );
    // normal comments only, not pingbacks; since WordPress 5.5 their type is 'comment' instead of ''
    $type      = isset( $commentdata['comment_type'] ) ? $commentdata['comment_type'] : '';
    $is_review = 'post' === $post_type && in_array( $type, array( '', 'comment' ), true );

    if ( $is_review && empty( $commentdata['comment_parent'] ) ) {
        $rating = isset( $_POST['ha_rating'] ) ? absint( $_POST['ha_rating'] ) : 0;

        if ( $rating < 1 || $rating > 5 ) {
            wp_die( esc_html__( 'Please choose a rating from 1 to 5.', 'textdomain' ), '', array( 'back_link' => true ) );
        }
    }

    return $commentdata;
} );

add_action( 'comment_post', function ( $comment_id ) {
    $rating = isset( $_POST['ha_rating'] ) ? absint( $_POST['ha_rating'] ) : 0;

    if ( $rating >= 1 && $rating <= 5 ) {
        update_comment_meta( $comment_id, 'ha_rating', $rating );
    }
} );

Replies (comments with a parent) are not forced to have a rating, so a discussion under a review stays possible.

Showing the rating

<?php
add_filter( 'comment_text', function ( $text, $comment ) {
    $rating = $comment ? (int) get_comment_meta( $comment->comment_ID, 'ha_rating', true ) : 0;

    if ( $rating ) {
        $stars = str_repeat( '★', $rating ) . str_repeat( '☆', 5 - $rating );
        $text  = '<p class="comment-rating" aria-label="' . esc_attr( sprintf( __( '%d out of 5', 'textdomain' ), $rating ) ) . '">' . $stars . '</p>' . $text;
    }

    return $text;
}, 10, 2 );

The average

<?php
function ha_average_rating( $post_id ) {
    global $wpdb;

    $avg = $wpdb->get_var( $wpdb->prepare(
        "SELECT AVG( CAST( cm.meta_value AS UNSIGNED ) )
         FROM {$wpdb->commentmeta} cm
         INNER JOIN {$wpdb->comments} c ON c.comment_ID = cm.comment_id
         WHERE cm.meta_key = 'ha_rating' AND c.comment_post_ID = %d AND c.comment_approved = '1'",
        $post_id
    ) );

    return $avg ? round( (float) $avg, 1 ) : 0;
}

Only approved comments count, so spam and comments in moderation do not change the rating. On a busy site, store the result in post meta when a comment is approved or deleted, instead of calculating it on every view.

NOTE: Comment forms are open to everybody, so treat the rating like any other input: accept only the values 1 to 5, as above. And if the average is shown to search engines as structured data, it must be based on real reviews of the thing on the page; ratings of blog posts by their readers are not eligible for review stars in Google.