将数字转换为星星

Convert number to Stars

我创建了这个将数字转换为星级的简码。目前,短代码有效但不完全:

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');

假设我的字段值 note_independant = 3。

简码输出是★★★而不是★★★☆☆。

我在使用像 3.5 这样的带小数的数字时也遇到了问题。短代码不会输出半星...

  1. 先去掉aria-hidden="true"显示全空半星。阅读更多关于 aria-hidden
  2. ',' 替换为 '.' 以使用小数

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

否则您的代码运行良好:Check Online

问题可能取决于您使用的 Awesome 字体版本

在 FA 5.5 中,对半星使用 fa fa-star-half-alt,对空白星使用 far fa-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>

并且不要忘记在 if (strpos($starNumber,',')) {

中用点 . 替换逗号 ,

您可以改用上述解决方案或 WordPress 星级评分功能。

了解更多关于 wp_star_rating here