将数字转换为星星

时间:2018-11-03 09:02:46

标签: php wordpress shortcode rating

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

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的十进制数字时,我还有一个问题。简码不会输出半颗星...

3 个答案:

答案 0 :(得分:2)

问题可能取决于您所使用的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,',')) {

答案 1 :(得分:1)

  1. 首先删除aria-hidden="true",以显示所有空白和半星号。进一步了解aria-hidden
  2. ','替换为'.'以使用十进制

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

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

答案 2 :(得分:0)

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

详细了解wp_star_rating here