diff --git a/README.txt b/README.txt index fe3c26e..4763ab9 100644 --- a/README.txt +++ b/README.txt @@ -147,3 +147,8 @@ to: } +For enabling aggregateRating functionality +(read more on https://developers.google.com/search/docs/data-types/review), +the site should have enabled "Voting API" and any UI module related to "Voting API", for example, +Votingapi Widgets (https://www.drupal.org/project/votingapi_widgets) or +Fivestar (https://www.drupal.org/project/fivestar). \ No newline at end of file diff --git a/schema_article/src/Plugin/metatag/Tag/SchemaArticleAggregateRating.php b/schema_article/src/Plugin/metatag/Tag/SchemaArticleAggregateRating.php new file mode 100644 index 0000000..d2401b5 --- /dev/null +++ b/schema_article/src/Plugin/metatag/Tag/SchemaArticleAggregateRating.php @@ -0,0 +1,104 @@ +moduleExists('votingapi')) { + $this->votingapiEnabled = TRUE; + } + } + + /** + * Generate a form element for this meta tag. + */ + public function form(array $element = []) { + $form = []; + + if ($this->votingapiEnabled) { + $form = [ + '#type' => 'checkbox', + '#title' => $this->label(), + '#description' => $this->description(), + '#default_value' => $this->value(), + ]; + } + + return $form; + } + + /** + * {@inheritDoc} + */ + public function output() { + $element = parent::output(); + + if (!empty($element['#attributes']['content'])) { + // Load the current node. + $node = \Drupal::routeMatch()->getParameter('node'); + + // Get rating from votingapi. + $results = []; + $query = \Drupal::database()->select('votingapi_result', 'v'); + $query->fields('v', ['type', 'function', 'value']); + $query->condition('entity_type', 'node'); + $query->condition('entity_id', $node->id()); + $result = $query->execute(); + while ($row = $result->fetchAssoc()) { + $results[$row['type']][$row['function']] = $row['value']; + } + + if (!empty($results)) { + $element['#attributes']['content'] = [ + "@type" => "AggregateRating", + "ratingValue" => $results['vote']['vote_average'], + "bestRating" => 5, + "worstRating" => 1, + "ratingCount" => $results['vote']['vote_count'], + ]; + } + else { + return FALSE; + } + + } + + return $element; + } + +}