您始终可以在 gatsby-node.js 中创建单独的查询,在其中创建动态 WordPress 页面并通过上下文发送 databaseId 并在模板中使用它来设置 bodyAttributes。例如:
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
},
})
})
}
然后,在您的模板中(./src/templates/post.js 遵循上一个示例):
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
}
}
}
}
}
}
}
`
修改自https://github.com/gatsbyjs/gatsby/blob/master/starters/gatsby-starter-wordpress-blog/src/templates/Post.js
通过上下文 API 发送的数据在props.pageContext 中可用。
如果您的databaseId 在allWpPost 节点中不可用,您可以从以下节点的页面/模板查询中提取它:
post: wpPost(id: { eq: $id })
当然,调整和调整上面的 sn-ps 以适合您的规格。