# 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.

- Type: PHP
- Runs: Run everywhere
- Category: [Forms](https://wpide.com/library/category/forms/)
- Tags: comments, ratings, reviews
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/form-comment-star-rating/

## Code

```php
$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 use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Star Rating Field in Comments" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
