【问题标题】:Convert number to star rating php shortcode?将数字转换为星级 php 短代码?
【发布时间】:2020-06-17 09:59:42
【问题描述】:

我使用以下代码在我的网站上的短代码中生成星级。

function Getrating() {

$starNumber = "5";

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('starrating', 'Getrating');

我是 PHP 新手,非常困惑。我遇到的问题是,如何使$starNumber 成为可以在短代码中更改的可变数字?例如,如果我想用 [starrating rating="3.5"] 这样的简码显示 3.5 颗星

我尝试的一切似乎都破坏了简码。任何帮助将不胜感激。

谢谢!

【问题讨论】:

  • 不明白你的意思。如果您想显示评分,请将其作为参数传递给函数 ex:- Getrating(3.5) 并在函数定义中使用 Getrating($starNumber)

标签: php wordpress wordpress-shortcode


【解决方案1】:

您需要将星号作为参数发送给函数,如下所示:

function Getrating($atts) {
    //starNumber has a default value of 5 if it is not set in the short code
    extract(shortcode_atts(array(
        'starNumber' => 5,
    ), $atts));

    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;

}

//register the shortcode
function wp_shortcodes_init(){
    add_shortcode('starrating', 'Getrating');
}

//tie the shortcode to WordPress initialization action
add_action('init', 'wp_shortcodes_init');

在 CMS 中使用短代码时,请像这样 [starrating starNumber="5"]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-07
    • 1970-01-01
    • 2011-11-15
    • 2011-03-14
    • 1970-01-01
    相关资源
    最近更新 更多