Add images to sitemap xml hooking into xmlsitemap in Drupal

Add images to sitemap xml hooking into xmlsitemap in Drupal

There are a few solutions for adding an image sitemap xml for easier indexing of your images in google, bing, etc., but found them be too selective or not updated when you added/edited a node. With 2 simple hooks, you can hook into xmlsitemap to add the images per url.

First, add your xml schema for images so search engines can understand the image xml added to your sitemap

/**
 * Implements hook_xmlsitemap_root_attributes_alter().
 */
function mymodule_xmlsitemap_root_attributes_alter(&$attributes, $sitemap) {
  $attributes['xmlns:image'] = 'http://www.google.com/schemas/sitemap-image/1.1';
}

Next, add the image for each url. The hook is run for each xmlsitemap element (url), so basically checking to see if its a node/term and adding any image referenced from the node.

/**
 * Implements hook_xmlsitemap_element_alter().
 */
function mymodule_xmlsitemap_element_alter(array &$element, array $link, $sitemap) {
  if ($link['type'] == 'node') { // make sure its a node
    $fields = field_info_instances('node', $link['subtype']); // get all fields for content type
    $node = '';
    foreach ($fields as $field_name => $field) { // go through all fields of content type
      if (strpos($field_name, '_image') !== FALSE) { // I named all of my image fields ending in _image
        if (!$node) { // if multiple image fields on same node, don't have to keep loading same node
          $node = node_load($link['id']);
        }
        if ($field_image_items = field_get_items('node', $node, $field_name)) { // get all images in field
          foreach ($field_image_items as $item) {
            if (isset($item['uri'])) {
              // add image xml to element
              $element[] =  array(
                'key' => 'image:image',
                'value' => array('image:loc' => file_create_url($item['uri'])),
              );
            }
          }
        }
      }
    }
  }
}

This will result in something like this:

<url>
  <loc>http://mysite.com/my-article</loc>
  <image:image>
    <image:loc>http://mysite.com/sites/default/files/my-image.jpg</image:loc>
  </image:image>
</url>

Good Luck!!

Comments are closed.