You can always create a separate query in your gatsby-node.js
, where you create your dynamic WordPress pages and send via context the databaseId
and use it in the tempalte to set the bodyAttributes
. For example:
const path = require(`path`)
const { slash } = require(`gatsby-core-utils`)
exports.createPages = async ({ graphql, actions }) => {
const { createPage } = actions
// query content for WordPress posts
const {
data: {
allWpPost: { nodes: allPosts },
},
} = await graphql(`
query {
allWpPost {
nodes {
id
uri
databaseId
}
}
}
`)
const postTemplate = path.resolve(`./src/templates/post.js`)
allPosts.forEach(post => {
createPage({
path: post.uri,
component: slash(postTemplate),
context: {
id: post.id,
databaseId: post.databaseId
},
})
})
}
Then, in your template (./src/templates/post.js
following the previous example):
const BlogPostTemplate = ({ data, pageContext }) => {
return (
<Layout>
<Helmet bodyAttributes={{
class: `dynamic-${pageContext.databaseId}-class-will-go-here`
}} >
</Helmet>
<h1>Your post </h1>
</Layout>
)
}
export default BlogPostTemplate
export const pageQuery = graphql`
query BlogPostById(
# these variables are passed in via createPage.pageContext in gatsby-node.js
$id: String!
$previousPostId: String
$nextPostId: String
) {
# selecting the current post by id
post: wpPost(id: { eq: $id }) {
id
excerpt
content
title
date(formatString: "MMMM DD, YYYY")
featuredImage {
node {
altText
localFile {
childImageSharp {
fluid(maxWidth: 1000, quality: 100) {
...GatsbyImageSharpFluid_tracedSVG
}
}
}
}
}
}
}
`
Modified from https://github.com/gatsbyjs/gatsby/blob/master/starters/gatsby-starter-wordpress-blog/src/templates/Post.js
The data sent through context API is available in props.pageContext
.
In case your databaseId
is not available in allWpPost
node, you can extract it either way from the page/template query in the following node:
post: wpPost(id: { eq: $id })
Of course, adapt and tweak the snippets above to fit your specifications.