1

I want to create a simple star rating system based on the number displayed.

I have 1, 1.5, 2, 2.5, 3, 3.5 4, 4.5 and 5 where i have a full star and a half star.

I use the following code to display the number but i want to replace the number with stars.

  <?php if ( function_exists( 'the_field' ) ) {
           $value = get_field( "rating" );
           echo $value; }
  <?
user38208
  • 1,078
  • 1
  • 15
  • 31
  • 1
    Possible duplicate of [Converting numbers to visual rating (stars)?](http://stackoverflow.com/questions/10250825/converting-numbers-to-visual-rating-stars) – Kunjan Thadani Oct 29 '15 at 10:08
  • [Click here](http://stackoverflow.com/q/36491315/798371) for an answered version of this same question. – WBT Apr 08 '16 at 05:46

2 Answers2

1

Try PHP String Repeat function

<p>
    <?php echo str_repeat('<i class="fa fa-star"></i> ',get_field("rating")); ?>
    <?php echo is_float(get_field("rating")) ? '<i class="fa fa-star-half"></i>' : ''; ?>
</p>
Rajasekar D
  • 450
  • 2
  • 11
  • 23
  • While this code snippet may solve the question, [including an explanation](//meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. Please also try not to crowd your code with explanatory comments, as this reduces the readability of both the code and the explanations! – Blue Jul 30 '16 at 19:58
1

For those who may not understand RajaSekar's answer, including a link to the FontAwesome css library in your site header to have class fa, fa-star and fa-star-half.

E.g.

<html>
<head>
    <link rel="stylesheet" href="path/to/font-awesome/css/font-awesome.min.css" />
</head>
<body>
    <p>
        <?php echo str_repeat('<i class="fa fa-star"></i> ',get_field("rating")); ?>
        <?php echo is_float(get_field("rating")) ? '<i class="fa fa-star-half"></i>' : ''; ?>
    </p>
</body> 

You can download FontAwesome at http://fontawesome.io/