Skip to content Skip to sidebar Skip to footer

Stop Gatsby Blog Post Slug From Including Individual Post Folders

I have encountered a problem while making a personal Gatsby site whereby blog post files are having thier unique folders included in the slug. For example a file structure of: data

Solution 1:

Fixed by looking at other blog examples.

Post filename needs to be index.md or index.mdx

Solution 2:

I am sure there is a better way but I was able to solve it by making changes in gatsby-node.js to only take the substring after the last slash (/) in from the file path. If someone knows a better way I will be glad to know that.

Old:

exports.onCreateNode = ({ node, actions, getNode }) => {
  const { createNodeField } = actions

  if (node.internal.type === `MarkdownRemark`) {
    const value = createFilePath({ node, getNode })
    createNodeField({
      name: `slug`,
      node,
      value,
    })
  }
}

New:

exports.onCreateNode = ({ node, actions, getNode }) => {
  const { createNodeField } = actions

  if (node.internal.type === `MarkdownRemark`) {
    const value = createFilePath({ node, getNode, trailingSlash:false })
    createNodeField({
      name: `slug`,
      node,
      value: `${value.indexOf("/") > -1 ? value.substring(value.lastIndexOf("/")) : value}`,
    })
  }
}

Post a Comment for "Stop Gatsby Blog Post Slug From Including Individual Post Folders"