Halloween Sale 15% off Ends in See the plans
PHP

Star Rating Field in Comments

Adds an optional 1 to 5 star rating to the comment form, saves it with the comment and shows the stars above the comment text, for review-style posts.

Don’t have WPIDE yet? Install it on your site

Code

$wpide_rating_types = array( 'post' ); // Post types that get the rating field.

$wpide_rating_field = function () use ( $wpide_rating_types ) {
    if ( ! is_singular( $wpide_rating_types ) ) {
        return;
    }

    echo '<fieldset class="comment-form-rating" style="border:0;padding:0;margin:0 0 1em;"><legend>Your rating (optional)</legend>';
    for ( $i = 5; $i >= 1; $i-- ) {
        printf( '<label style="margin-right:.6em;"><input type="radio" name="wpide_rating" value="%1$d"> <span aria-hidden="true">%2$s</span><span class="screen-reader-text">%1$d stars</span></label>', (int) $i, esc_html( str_repeat( '★', $i ) ) );
    }
    echo '</fieldset>';
};

add_action( 'comment_form_logged_in_after', $wpide_rating_field );
add_action( 'comment_form_after_fields', $wpide_rating_field );

add_action( 'comment_post', function ( $comment_id ) use ( $wpide_rating_types ) {
    $rating = isset( $_POST['wpide_rating'] ) ? absint( $_POST['wpide_rating'] ) : 0;
    $post   = get_post( (int) get_comment( $comment_id )->comment_post_ID );

    if ( $rating >= 1 && $rating <= 5 && $post && in_array( $post->post_type, $wpide_rating_types, true ) ) {
        add_comment_meta( $comment_id, 'wpide_rating', $rating, true );
    }
} );

add_filter( 'comment_text', function ( $text, $comment = null ) {
    if ( ! $comment || is_admin() ) {
        return $text;
    }

    $rating = (int) get_comment_meta( $comment->comment_ID, 'wpide_rating', true );

    return $rating ? sprintf( '<p class="comment-rating" aria-label="%1$d out of 5 stars"><span aria-hidden="true">%2$s</span></p>', $rating, esc_html( str_repeat( '★', $rating ) . str_repeat( '☆', 5 - $rating ) ) ) . $text : $text;
}, 10, 2 );

Notes

Limit it to certain post types with the list at the top; ratings are stored as comment meta named wpide_rating.

How to add this snippet

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.