Adding custom links to sitemap.xml via hook_update_N

XML Sitemap is a very useful module to get a proper sitemap.xml file for a Drupal site. Configuration is quite straightforward and usage is very intuitive, but there is a catch: moving custom links from dev to stage/prod is not as easy as exporting with Features. Let's take a look at a method for doing it in Drupal 7 by leveraging hook_update_N().

By looking at xmlsitemap_custom.admin.module it is possible to know how that module saves custom links to the xmlsitemap table, which is the exact same method that we can use to put special paths into the sitemap.xml, by using code and not the UI. A common use case for this is landing pages created with Panels, since none of the helper modules bundled with xmlsitemap offers specialized support for panel pages.

Let's take a look at the code, with detailed comments explaining how it works:

/**
 * Implementation of hook_update_N()
 */
// N is 7101 here, assuming it's the first update for version 1 of MYMODULE
function MYMODULE_update_7101() {
  drupal_load('module', 'xmlsitemap');

  // Simple array with aliases for the custom links
  $paths = array(
    'alias-1',
    'alias-2',
  );

  $link = array(
    'type' => 'mymodule', // Unique "namespace"
    'id' => 0,
    'loc' => '',
    'priority' => '0.5', // Normal priority, can be increased if custom links require it
    'changefreq' => '86400', // 1 day = 24 h * 60 m * 60 s
    'language' => LANGUAGE_NONE
  );

  foreach($paths as $path) {
    $link['loc'] = drupal_get_normal_path($path, LANGUAGE_NONE);
    $link['id']++;
    xmlsitemap_link_save($link);
  }
}

Once the code is properly implemented, it's just a matter of running drush updb to run the updates on the target environment.