PHP snippet to print fivestar rating?

Macarro - September 24, 2009 - 12:29
Project:Fivestar
Version:5.x-1.9
Component:Code
Category:support request
Priority:normal
Assigned:Unassigned
Status:active
Description

Hi

I would like to get the raw fivestar average value simply as a number to do some manipulation with it. I'm trying with the function

votingapi_get_voting_result($content_type, $content_id, $value_type, $tag, $function)

but I'm not sure if this is the right function and what parameters to use. I would appreciate any help with this issue.

Kind regards.

#1

t_l - October 30, 2009 - 15:40

Hello,

I would use something like this:

  //i trust you know the node_type?  it would be in the content types area. 'story', 'page', etc are defaults.  additionally, you'll need the nid (node ID) you want to grab the votes for.  so, i'm assuming you have access to $node through the theme or through hook_nodeapi in your custom module.  lastly, these votingapi functions return an object.
 
  //votingapi has different mathematical 'functions', this line grabs the number of votes or 'count'
  $count = votingapi_get_voting_result($node->type, $node->nid, 'percent', 'vote', 'count');

  //this line grabs the average for all votes
  $average = votingapi_get_voting_result($node->type, $node->nid, 'percent', 'vote', 'average');

  //here we use number_format to make output consistently have one decimal place and make it out of 5,  $average->value would otherwise be out of 100.  not really sure what kind of manipulation you want to do, so this is just an example.
  $output = '<div class="my-ratings">(' . number_format($average->value*.05, 1)  . '/5.0, ' . $count->value .' Reviews)</div>';

  //not sure where you are using this code, but you could use it in the theme, eg node-my_node_type.tpl.php .  and you would then need to print $output.
  print $output;

hope that helps.

 
 

Drupal is a registered trademark of Dries Buytaert.