How to Alter XML Sitemap Entries in Drupal 8 Programmatically Using PHP

site map creation in drupal 8

Drupal 8 is one of the most secured CMS (Content Management System) software available in addition to WordPress and Joomla. Drupal does not have a Theme or Plugin market place like in WordPress. That is why all manual customizations require some knowledge about custom modules on Drupal. All websites need a Sitemap listing with all useful links so that it can be submitted to Google Search Console or Webmaster tools directly. We teach you how to alter XML sitemap entries manually to suit your needs.

Alter XML Sitemap Entries in Drupal 8

Before altering XML Sitemap entries, you need to generate an XML Sitemap file and Path using a module called XMLSitemap. It is a good practice to regularly update sitemap.xml file. XMLSitemap allows you to make new entries into the sitemap file automatically at every Cron run. After CRON is run, XMLSitemap automatically submits the sitemap to Google and Bing Search Consoles. Problem comes with Unpublished or Draft Nodes which automatically appear in your sitemap.xml file all of a sudden. Drupal 8 serves sitemap from the Root path itself.

Example:

https://www.mysite.com/sitemap.xml

Problem with inclusion of Unpublished Nodes in Sitemap.xml

Article may not be fully composed and written. This unfinished post will be crawled by search engines and they think you are writing posts with less quality. If the half baked post is indexed, it appears in SERP i.e Search Engine Results Page. End user thinks negative about the half written post from your website.

Problem without using Draft Feature from Drupal 8

No one is master in writing web articles in one go. They keep on adding content in one or two paragraphs at a time and save draft. They reopen the draft add some more content and save. If the editor feels the post is complete, he will publish it at last. But if the Drafting feature is not enabled or used, where does the editor or contributor save all his article content. No where other than some email or MS Word file. It looks ugly in this 21st century. So we want this Draft Feature from Drupal 8.

Steps to alter XMLSitemap programmatically in Drupal 8

  1. Create a Custom Module in Drupal 8.
  2. If you are already using a Custom Module, add the below PHP function to exclude Unpublished Nodes from Sitemap.xml
function mymodule_xmlsitemap_link_alter(&$link) {
 
    if ($link['type'] == 'node')
    {
      $node = node_load($link['id']);
      if(($node->get('status')->value == 0))
      {
        \Drupal::logger('mymodule')->notice($node->getTitle());
         $link['access'] = 0;
      }
    }
}

A value of 0 excludes the URL entry. A Value of 1 makes URL Entry into the sitemap.

This is how you alter XML Sitemap entries in a Custom Drupal 8 Module. You can include any other conditions like NodeType or the content of any node field to either include or exclude the content URL in sitemap.xml file.