You are here

amp_adsense.module in Accelerated Mobile Pages (AMP) 7

AMP integration for the Adsense module.

File

modules/amp_adsense/amp_adsense.module
View source
<?php

/**
 * @file
 *  AMP integration for the Adsense module.
 */

/**
 * Implements hook_block_view_alter().
 */
function amp_adsense_block_view_alter(&$data, $block) {
  if ($block->module == 'adsense_managed') {
    if (amp_is_amp_request()) {

      // Gather information about the block.
      $block_config = _adsense_managed_get_block_config($block->delta);

      // The block key are not named. The 2nd item in the array is format.
      $format = $block_config[1];
      $ad = adsense_ad_formats($format);

      // Get the required block variables.
      $height = $ad['height'];
      $width = $ad['width'];
      $data_ad_client = variable_get('adsense_basic_id');

      // The block key are not named. The 3nd item in the array is ad slot.
      $data_ad_slot = $block_config[2];
      $data['content'] = array(
        '#theme' => 'amp_ad',
        '#adtype' => 'adsense',
        '#height' => $height,
        '#width' => $width,
        '#slot_attributes_array' => array(
          'data-ad-client' => $data_ad_client,
          'data-ad-slot' => $data_ad_slot,
        ),
      );
    }
  }
}

/**
 * Implements hook_theme().
 */
function amp_adsense_theme() {
  $theme = array(
    'amp_ad' => array(
      'variables' => array(
        'adtype' => NULL,
        'height' => NULL,
        'width' => NULL,
        'slot_attributes' => NULL,
        'slot_attributes_array' => array(),
      ),
      'template' => 'amp-ad',
    ),
  );
  return $theme;
}

/**
 * A callback to render amp_ad with js library added to head.
 *
 * @return
 *   The passed-in element with the js library necessary for the amp-ad
 *   element added to head.
 */
function _amp_adsense_headers() {
  $head_js = array(
    '#tag' => 'script',
    '#type' => 'html_tag',
    '#attributes' => array(
      'src' => 'https://cdn.ampproject.org/v0/amp-ad-0.1.js',
      'async' => NULL,
      'custom-element' => 'amp-ad',
    ),
  );
  drupal_add_html_head($head_js, 'amp-ad');
}

/**
 * Implements hook_preprocess_amp_ad().
 */
function amp_adsense_preprocess_amp_ad() {
  if (!amp_is_amp_request()) {
    return;
  }
  _amp_adsense_headers();
}

Functions

Namesort descending Description
amp_adsense_block_view_alter Implements hook_block_view_alter().
amp_adsense_preprocess_amp_ad Implements hook_preprocess_amp_ad().
amp_adsense_theme Implements hook_theme().
_amp_adsense_headers A callback to render amp_ad with js library added to head.