Skip to content
Advertisement

Convert number to star rating php shortcode?

I’ve used the following code in order to generate a star rating inside a shortcode on my site.

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

I’m new to PHP and incredibly confused. The issue I have is, how can I make $starNumber a variable number that I can change inside the shortcode? For example, if I wanted to show 3.5 stars with a shortcode such as [starrating rating="3.5"]

Everything I try only seems to break the shortcode. Any help would be greatly appreciated.

Thanks!

Advertisement

Answer

You need to send the star number as a parameter to the function as follows:

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

When using the shortcode in the CMS use it like this [starrating starNumber=”5″]

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement