Duderino9000
Duderino9000

Reputation: 2597

Gatsby sitemap plugin - only include certain URLs?

I know I can exclude urls with the exclude array in the options object with gatsby-plugin-sitemap, but is there a way to require all URLs have some string? Mainly looking to require urls added to the sitemap contain either en-us or es-us

 {
    resolve: `gatsby-plugin-sitemap`,
    options: {
      exclude: [`all urls must contain "en-us" or "es-us"`],
    },
  },

Thanks!

UPDATE!! Thanks to @MarkoCen I was able to get this working. I just used regex to add the URLS I wanted in my sitemap. Here's the code if anyone is interested. Note that I had to manually exclude /404 with this approach:

{
    resolve: `gatsby-plugin-sitemap`,
    options: {
      query: `
        {
          site {
            siteMetadata {
              siteUrl
            }
          }

          allSitePage {
            edges {
              node {
                path
              }
            }
          }
      }`,
      serialize: ({ site, allSitePage }) => {
        const links = [];
        for (let i = 0; i < allSitePage.edges.length; i++) {
          const { path } = allSitePage.edges[i].node;
          if (
            /products|404|unsupported|account/.test(path)
          ) {
            continue;
          } else if (/en-us|es-us/.test(path)) {
            links.push({
              url: site.siteMetadata.siteUrl + path,
              changefreq: 'daily',
              priority: 0.8,
            });
          }
        }
        return links;
      },
    },
  },

Upvotes: 1

Views: 876

Answers (1)

MarkoCen
MarkoCen

Reputation: 2324

you can build the sitemap from scratch with query and serialize options

{
    resolve: `gatsby-plugin-sitemap`,
    options: {
      output: `/sitemap.xml`,

      // use this query to fetch all the data needed for sitemap links
      query: `
        {
          site {
            siteMetadata {
            siteUrl
          }
          blogs {
            title
          }
          ...
        }
      `,
      serialize: ({ site, blogs }) => {
        const links = [];
        blogs.forEach(blog => {
          // add link with en-us prefix
          links.push({
            url: `${site.siteMetadata.siteUrl}/en-us/blog/${blog.title}`,
            changefreq: 'daily',
            priority: 0.8,
          });
          // add link with es-us prefix
          links.push({
            url: `${site.siteMetadata.siteUrl}/es-us/blog/${blog.title}`
            changefreq: 'daily',
            priority: 0.8,          
          });
        })

        // plugin will use returned links to generate sitemap, so only include the links you want to show!
        return links;
      }
    },
},

Upvotes: 3

Related Questions