Advertisement
geminilabs

[site-reviews] set rating number dynamically from custom rating fields

Oct 26th, 2020 (edited)
2,591
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.13 KB | None | 0 0
  1. /**
  2.  * Dynamically set the rating to the average of your custom rating fields.
  3.  * !IMPORTANT: make sure to remove the default rating field in your custom form for this to work.
  4.  * Paste this in your active theme's functions.php file.
  5.  * @param array $values
  6.  * @return array
  7.  */
  8. add_filter('site-reviews/create/review-values', function ($values, $request) {
  9.     if (!empty($values['rating'])) {
  10.         return $values; // don't set the overall rating if it already has a value
  11.     }
  12.     $fields = (array) get_post_meta($request->request->form, '_fields', true);
  13.     $ratings = [];
  14.     foreach ($fields as $field) {
  15.         if ('rating' === glsr_get($field, 'type')) {
  16.             $ratings[] = glsr_get($values, 'custom.'.glsr_get($field, 'name'), 0);
  17.         }
  18.     }
  19.     $ratings = array_filter($ratings); // remove empty custom rating values;
  20.     if (empty($ratings)) {
  21.         return $value; // don't set the overall rating if there are no custom rating fields
  22.     }
  23.     $ratingsCount = count($ratings);
  24.     $ratingsSum = array_sum($ratings);
  25.     $values['rating'] = round($ratingsSum / $ratingsCount);
  26.     return $values;
  27. }, 10, 2);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement