Fabien
Fabien

Reputation: 69

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...

Upvotes: 0

Views: 2616

Answers (3)

Ahmed Hassan
Ahmed Hassan

Reputation: 269

You can use either use above solutions or WordPress star rating function instead.

Learn more about wp_star_rating here

Upvotes: 0

ewwink
ewwink

Reputation: 19164

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,',')) {

Upvotes: 2

Niklesh Raut
Niklesh Raut

Reputation: 34914

  1. First remove aria-hidden="true" to display all blank and half star. Read more about aria-hidden
  2. Replace ',' to '.' to get work with decimal

      if (strpos($starNumber,'.')) {
    

Otherwise your code is working well : Check Online

Upvotes: 1

Related Questions