function google_appliance_page_attachments in Google Search Appliance 8
Implements hook_page_attachments().
File
- ./
google_appliance.module, line 62 - Google Appliance module file.
Code
function google_appliance_page_attachments(array &$attachments) {
// @todo This needs to be finished and tested.
$gsaSettings = Drupal::configFactory()
->get('google_appliance.settings')
->get();
// If configured, add JSON-LD for Google sitelinks search box.
if (isset($gsaSettings['display_settings']['sitelinks_search_box']) && $gsaSettings['display_settings']['sitelinks_search_box'] === TRUE && Drupal::service('path.matcher')
->isFrontPage()) {
$request = Drupal::request();
$canonicalUrl = $request
->getSchemeAndHttpHost() . $request
->getBasePath();
// Google recommended practices suggest that the "url" key in the JSON-LD
// and the homepage canonical URL must match. This checks for the canonical
// metatag value and substitutes in place of the default provided above.
if (isset($attachments['metatag_canonical']['#value'])) {
$canonicalUrl = $attachments['metatag_canonical']['#value'];
}
$targetUrl = Url::fromRoute(SearchViewRoute::ROUTE_NAME)
->toString(TRUE)
->getGeneratedUrl() . '/{search_query}';
$jsld = [
'@context' => 'http://schema.org',
'@type' => 'WebSite',
'url' => $canonicalUrl,
'potentialAction' => [
'@type' => 'SearchAction',
'target' => $targetUrl,
'query-input' => 'required name=search_term_string',
],
];
if (empty($attachments['#attached'])) {
$attachments['#attached'] = [];
}
if (empty($attachments['#attached']['html_head'])) {
$attachments['#attached']['html_head'] = [];
}
$jsldAttachment = [
'#type' => 'html_tag',
'#tag' => 'script',
'#attributes' => [
'type' => 'application/ld+json',
],
'#value' => Json::encode($jsld),
];
$attachments['#attached']['html_head'][] = [
$jsldAttachment,
'google_appliance_slsb',
];
}
}