在Gatsby中,使用Wordpress作为数据源,使用不同的模板创建不同的页面



我有一个Gatsby网站,它正在从另一个Wordpress网站中提取数据。它可以动态地为帖子创建页面,但是一旦我添加新的自定义帖子类型,它只会为此创建页面,而不是帖子。所以基本上,它只为我添加到"gatsby-node.js"文件的最新帖子创建页面。看起来像这样:

const path = require(`path`)
exports.createPages = ({ graphql, actions }) => {
const { createPage } = actions
return graphql(`
{
allWordpressPost(sort: { fields: [date] }) {
edges {
node {
title
excerpt
content
slug
}
}
}
}
`).then(result => {
result.data.allWordpressPost.edges.forEach(({ node }) => {
createPage({
path: node.slug,
component: path.resolve(`./src/templates/blog-post.js`),
context: {
// This is the $slug variable
// passed to blog-post.js
slug: node.slug
},
})
})
})
}
//Create a page for each Property Post type
exports.createPages = ({ graphql, actions }) => {
const { createPage } = actions
return graphql(`
{
allWordpressWpProperty {
edges {
node {
slug
title
content
featured_media {
localFile {
childImageSharp {
original {
width
height
src
}
}
}
}
acf {
size
}
}
}
}
}
`).then(result => {
result.data.allWordpressWpProperty.edges.forEach(({ node }) => {
createPage({
path: node.slug,
component: path.resolve(`./src/templates/property.js`),
context: {
// This is the $slug variable
// passed to property.js
slug: node.slug
},
})
})
})
}

我得到的错误是"当我尝试访问博客文章时无法阅读未定义的"页面"。有没有办法为两者创建页面?

所以我认为你不应该导出createPages两次。

相反,将其导出一次,然后在同一函数中为两种类型的帖子创建页面。您可以轻松地将两者抽象为它们自己单独的async函数,并在createPagesawait它们,只是为了给您这种分离,以便您知道每一步都在创建哪些页面。

像这样:

import createBlogPosts from "../somewhere";
import createPropertyPosts from "../somewhere";
exports.createPages = async ({ graphql, actions }) => {
const { createPage } = actions;
await createBlogPosts({ graphql, createPage });
await createPropertyPosts({ graphql, createPage });
}

最终在同一函数下添加了两个查询,并使用了两次 createPage 函数,结果不同:

const path = require(`path`)
exports.createPages = ({ graphql, actions }) => {
const { createPage } = actions
return graphql(`
query {
allWordpressPost {
edges {
node {
title
excerpt
slug
link
}
}
}
allWordpressWpProperty {
edges {
node {
slug
title
content
featured_media {
localFile {
childImageSharp {
original {
width
height
src
}
}
}
}
acf {
size
}
}
}
}
}
`).then(result => {
result.data.allWordpressPost.edges.forEach(({ node }) => {
createPage({
path: node.slug,
component: path.resolve(`./src/templates/blog-post.js`),
context: {
// This is the $slug variable
// passed to blog-post.js
slug: node.slug
},
})
});
result.data.allWordpressWpProperty.edges.forEach(({ node }) => {
createPage({
path: node.slug,
component: path.resolve(`./src/templates/property.js`),
context: {
// This is the $slug variable
// passed to property.js
slug: node.slug
},
})
});
})
}

最新更新