I am using WP with the Avada theme and the built in Star Rating element as well as ACF Pro. Unfortunately I found out that the Star-Rating element adds a rating scheme to the footer of the website without asking. There is also no way to disable this. This is annoying
So I created my own shortcode based on the CSS code of the Star-Rating element.
It also works perfectly. Nevertheless, I have the feeling that there might still be potential for optimization.
The CSS code works as follows:
Example rating: 2.0 stars out of max 5.0
2x stars (filled)
3x stars (empty)
Example rating: 2.5 stars from max 5.0
2x stars (filled)
1x star (percentage filled: 50%)
2 stars (empty)
Example rating: 1.2 stars from max 5.0
1x star (filled)
1x star (percentage filled: 20%)
3x stars (empty)
Example rating: 4.6 stars from max 5.0
4x stars (filled)
1x star (percentage filled: 60%)
I have the following code now:
function show_star_rating_review()
{
ob_start();
global $post;
$rating = get_field('rating', $post);
$rate_arr = explode('.',$rating);
if ($rate_arr[1]) {
$rate_emp = 4 - $rate_arr[0];
} else {
$rate_emp = 5 - $rate_arr[0];
}
$x = 1;
$y = 1;
echo '<div class="awb-stars-rating awb-stars-rating-1 awb-stars-rating-no-text" aria-label="Rating: ' . $rating . ' out of 5">';
echo '<style>.awb-stars-rating-1 .awb-stars-rating-filled-icon{margin-right:2px;color:#ffd041;}.awb-stars-rating-1 .awb-stars-rating-empty-icon,.awb-stars-rating-1 .awb-stars-rating-partial-icon-wrapper{margin-right:2px;}.awb-stars-rating-1 .awb-stars-rating-partial-icon{color:#ffd041;}.awb-stars-rating-1 .awb-stars-rating-icons-wrapper{color:#dbdbdb;font-size:23px;}</style>';
echo '<div class="awb-stars-rating-icons-wrapper">';
while ($x <= $rate_arr[0]) {
$x++;
echo '<i class="fa-star fas awb-stars-rating-filled-icon"></i>';
}
if ($rate_arr[1]) {
echo '<i class="fa-star fas awb-stars-rating-partial-icon-wrapper"><i class="fa-star fas awb-stars-rating-partial-icon" style="width:' . $rate_arr[1] . '0%;"></i></i>';
}
if ($rate_emp > 0) {
while ($y <= $rate_emp) {
$y++;
echo '<i class="fa-star fas awb-stars-rating-empty-icon"></i>';
}
}
echo '</div>';
echo '</div>';
return ob_get_clean();
}
add_shortcode('ShowStarRatingReview', 'show_star_rating_review');
$rating is the ACF with the assigned rating. $rate_arr decomposes the rating into number before and number after the point.
If number after the point exists, so x.x rating then empty stars = 4 - number
before the point.
If number after the point exists, so x.0 rating then empty stars = 5 - number
before the point.
As I mentioned before, the code works without problems so far. I'm just wondering if maybe I've made the whole thing too complicated.
.5
of a point. \$\endgroup\$