Add lastmod, changefreq and changecount to sitemap.xml for taxonomy terms by the xmlsitemap module

Estimated reading time of this article: 1 minute 24 seconds

By default lastmod, changefreq and changecount are not written to the sitemap.xml for taxonomy terms by the xmlsitemap module. Fortunately, there is a hook for changing this. The result can be seen on sitemap.xml.

<?php
/**
 * Fetch all timestamps when a taxonomy term or his direct child was changed.
 *
 * @param $node
 *   A node object.
 * @return
 *   An array of UNIX timestamp integers.
 */
function _YOUR_MODULE_term_get_timestamps(stdClass $term) {
  static
$term_timestamps = array();

  if (!isset(
$term_timestamps[$term->tid])) {
   
$term_timestamps[$term->tid] = db_query("SELECT ti.created FROM {taxonomy_index} ti WHERE ti.tid = :tid
      UNION ALL
      SELECT ti.created FROM {taxonomy_term_hierarchy} th, {taxonomy_index} ti WHERE th.parent = :tid AND th.tid = ti.tid"
, array(':tid' => $term->tid))->fetchCol();
  }

  return
$term_timestamps[$term->tid];
}

/**
 * Add changefreq, changecount and lastmod for taxonomy terms.
 *
 * Implements hook_xmlsitemap_link_alter.
 *
 * @param $link
 *   An array with the data of the sitemap link.
 */
function YOUR_MODULE_xmlsitemap_link_alter(&$link) {
  if (
$link['type'] == 'taxonomy_term') {
   
// dpm($link, 'link');
   
$tid = $link['id'];
   
$term = taxonomy_term_load($tid);
   
// dpm($term);

    // Always recalculate changefreq and changecount.
   
$timestamps = _YOUR_MODULE_term_get_timestamps($term);
   
$link['changefreq'] = $term->tid ? xmlsitemap_calculate_changefreq($timestamps) : 0;
   
$link['changecount'] = $term->tid && (count($timestamps) > 0) ? count($timestamps) - 1 : 0;
   
$link['lastmod'] = count($timestamps) > 0 ? max($timestamps) : 0;
  }
}
?>