# Star Rating Shortcode

> Adds a [star_rating] shortcode that shows a rating such as 4.5 out of 5 as stars, with half stars and a text label for screen readers, for reviews and comparison posts.

- Type: PHP
- Runs: Run everywhere
- Category: [Content](https://wpide.com/library/category/content/)
- Tags: shortcodes, ratings, reviews
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/star-rating-shortcode/

## Code

```php
add_action( 'init', function () {
    add_shortcode( 'star_rating', function ( $atts ) {
        $atts   = shortcode_atts( array( 'rating' => 0, 'max' => 5, 'color' => '#f5a623', 'size' => '1.1em' ), $atts, 'star_rating' );
        $max    = max( 1, min( 10, (int) $atts['max'] ) );
        $rating = max( 0, min( $max, round( (float) $atts['rating'] * 2 ) / 2 ) );
        $star   = 'M12 2.8l2.9 5.9 6.5.9-4.7 4.6 1.1 6.4L12 17.6l-5.8 3 1.1-6.4-4.7-4.6 6.5-.9z';
        $id     = wp_unique_id( 'wpide-half-' );
        $out    = '';

        for ( $i = 1; $i <= $max; $i++ ) {
            $fill = $rating >= $i ? esc_attr( $atts['color'] ) : ( $rating >= $i - 0.5 ? 'url(#' . $id . ')' : 'none' );
            $out .= '<svg aria-hidden="true" focusable="false" viewBox="0 0 24 24" width="' . esc_attr( $atts['size'] ) . '" height="' . esc_attr( $atts['size'] ) . '" style="vertical-align:-0.15em"><path d="' . $star . '" fill="' . $fill . '" stroke="' . esc_attr( $atts['color'] ) . '" stroke-width="1.5" stroke-linejoin="round"/></svg>';
        }

        $defs = '<svg width="0" height="0" style="position:absolute" aria-hidden="true" focusable="false"><defs><linearGradient id="' . esc_attr( $id ) . '"><stop offset="50%" stop-color="' . esc_attr( $atts['color'] ) . '"/><stop offset="50%" stop-color="transparent"/></linearGradient></defs></svg>';

        return sprintf(
            '<span class="wpide-stars" role="img" aria-label="%s">%s%s</span>',
            esc_attr( sprintf( 'Rated %s out of %d', $rating, $max ) ),
            $defs,
            $out
        );
    } );
} );
```

## Notes

Example [star_rating rating="4.5" max="5" color="#f5a623"]; values are clamped between 0 and max.

## How to use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Star Rating Shortcode" 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/
