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.
Opens WPIDE on
Code
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 add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.