Skip to content

Commit

Permalink
Create nested URLs for pages
Browse files Browse the repository at this point in the history
  • Loading branch information
dajocarter committed Oct 30, 2018
1 parent 158673e commit e494293
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 4 deletions.
41 changes: 39 additions & 2 deletions gatsby-node.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,41 @@
const path = require('path')
const { createFilePath } = require('gatsby-source-filesystem')

/**
* Create nested paths
* e.g., /grandparent/parent/node-slug
* and add to node
*/
exports.sourceNodes = ({ getNodes, actions }) => {
const { createNodeField } = actions

// Grag all page nodes
const pageNodes = getNodes().filter(
node => node.internal.type === 'wordpress__PAGE'
)

// Build each node's full path
pageNodes.forEach(node => {
// Save the original node for use down below
const original = node
// Start with the node's slug
let newSlug = `/${node.slug}/`
// Recursively check for a parent and prepend parent's slug to newSlug
while (node.wordpress_parent) {
node = pageNodes.find(
parentNode => node.wordpress_parent === parentNode.wordpress_id
)
newSlug = `/${node.slug}${newSlug}`
}
// Add full path to node -- available at node.fields.path
createNodeField({
node: original,
name: `path`,
value: newSlug,
})
})
}

exports.createPages = ({ actions, graphql }) => {
const { createPage } = actions

Expand All @@ -10,7 +45,9 @@ exports.createPages = ({ actions, graphql }) => {
edges {
node {
id
slug
fields {
path
}
status
template
}
Expand All @@ -35,7 +72,7 @@ exports.createPages = ({ actions, graphql }) => {

pages.forEach(({ node }) => {
createPage({
path: `/${node.slug}/`,
path: node.fields.path,
component: pageTemplate,
context: {
id: node.id,
Expand Down
6 changes: 4 additions & 2 deletions src/components/Navbar.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@ const Navbar = () => (
node {
id
title
slug
fields {
path
}
}
}
}
Expand All @@ -32,7 +34,7 @@ const Navbar = () => (
{data.allWordpressPage.edges.map(edge => (
<Link
className="navbar-item"
to={edge.node.slug}
to={edge.node.fields.path}
key={edge.node.id}
>
{edge.node.title}
Expand Down

0 comments on commit e494293

Please sign in to comment.