Support

Account

Home Forums General Issues Translate number (1-5) to stars on front end

Solved

Translate number (1-5) to stars on front end

  • Hi there,

    I’m trying to make a number field in ACF, and translating that number to the corresponding amount of stars on the front end. I don’t need user votes or anything like that, the admin decides the rating.

    I use FontAwesome now for 0%/50%/100% stars, so it would be nice if it can use that somehow.

    I could manually add this (below) to a field, but that feels a bit clunky.. Also, i’d like to be able to sort/filter on ratings one day, so I reckon a number would be a good value then.

    4.5 rating would translat to:

    <i class="fa fa-star" aria-hidden="true"></i> <i class="fa fa-star" aria-hidden="true"></i> <i class="fa fa-star" aria-hidden="true"></i> <i class="fa fa-star-half-o" aria-hidden="true"></i> <i class="fa fa-star-o" aria-hidden="true"></i>

    Thanks in advance!

  • Found a snippet and modified it a little, seems to work now!

    <?php
    	$starNumber = get_field('rating');
    
        for($x=1;$x<=$starNumber;$x++) {
            echo '<i class="fa fa-star" aria-hidden="true"></i>';
        }
        if (strpos($starNumber,'.')) {
            echo '<i class="fa fa-star-half-o" aria-hidden="true"></i>';
            $x++;
        }
        while ($x<=5) {
            echo '<i class="fa fa-star-o" aria-hidden="true"></i>';
            $x++;
        }
    ?>

    For anyone using this: it’s based on the stars from FontAwesome, with the smallest step being .5

Viewing 2 posts - 1 through 2 (of 2 total)

The topic ‘Translate number (1-5) to stars on front end’ is closed to new replies.