Search code examples
phpwordpressshortcoderating

Convert number to Stars


I've created this shortcode that converts a number to a star rating. At the moment, the shortcode works but not fully :

function Shortcode() {

$starNumber = get_field('note_independant');

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

return $output;

 }

add_shortcode('helloworld', 'Shortcode');

Let say my field value note_independant = 3.

The shortcode output is ★★★ instead of ★★★☆☆.

I have also an issue when using a number with decimal like 3.5. The shortcode won't output half stars...


Solution

  • the problem may depend on font Awesome version you use

    in FA 5.5 use fa fa-star-half-alt for half star and far fa-star for blank star

    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.5.0/css/all.css" integrity="sha384-B4dIYHKNBt8Bc12p+WXckhzcICo0wtJAoU8YZTY5qE0Id1GSseTk6S+L3BlXeVIU" crossorigin="anonymous">
    
    <div class="wrap">
      <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-alt" aria-hidden="true"></i> 
      <i class="far fa-star" aria-hidden="true"></i>
    </div>

    and don't forget to replace comma , with dot . in if (strpos($starNumber,',')) {