You are here

function structured_data_preprocess_html in Structured Data (JSON+LD Rich Snippets) 7

Implements template_preprocess_html().

Add the necesarry json-ld to the page header.

File

./structured_data.module, line 40
Annotate your content to generate Rich Search Snippets.

Code

function structured_data_preprocess_html(&$vars) {

  // Without more information, we assume every website is just a website.
  $structured_data = array(
    '@context' => 'http://schema.org',
    '@type' => 'WebSite',
  );

  // Override if a business type was selected.
  if ($schema_type = variable_get('structured_data_business_type', FALSE)) {
    $structured_data['@type'] = $schema_type;
  }

  // Add site name info.
  $structured_data['name'] = structured_data_get_site_name();

  // Get the alternative site name.
  if ($alternative_site_name = variable_get('structured_data_site_name_alternative', FALSE)) {
    $structured_data['alternateName'] = $alternative_site_name;
  }

  // If metatag has set a cononical URL, add that here too.
  $head_elements = drupal_add_html_head();
  if (!empty($head_elements['metatag_canonical'])) {
    $structured_data['url'] = $head_elements['metatag_canonical']['#value'];
  }
  else {

    // URL is required, so we fall back to using the site home page.
    $structured_data['url'] = url('', array(
      'absolute' => TRUE,
    ));
  }

  // Add site logo.
  $structured_data['logo'] = structured_data_get_site_logo();

  // Add local business info.
  $local_data = structured_data_get_local_info();
  $structured_data = array_merge($structured_data, $local_data);

  // Add corporate contact info.
  $corp_data = structured_data_get_corporate_info();
  $structured_data = array_merge($structured_data, $corp_data);

  //Add social links.
  $social_links = structured_data_get_social_link_info();
  if ($social_links) {
    $structured_data['sameAs'] = $social_links;
  }

  // If there is any sructured data, add it to the page.
  if (!empty($structured_data)) {
    $json_ld_script = array(
      '#tag' => 'script',
      '#attributes' => array(
        'type' => 'application/ld+json',
      ),
      '#value' => defined('JSON_UNESCAPED_SLASHES') ? json_encode($structured_data, JSON_UNESCAPED_SLASHES) : json_encode($structured_data),
    );
    drupal_add_html_head($json_ld_script, 'structured_data_json_ld');
  }
}