使用Gatsby.js与WordPress进行集成,展示文章列表并显示详细内容
我将记下从WordPress迁移至Gatsby.js的过程中获取和展示WordPress文章信息的协作步骤。
以下内容是基于使用CLI创建的gatsby new项目进行的。
添加WordPress插件
与WordPress的集成是通过gatsby-source-wordpress来实现的,所以需要下载该软件包。
$ yarn add gatsby-source-wordpress
然后在gatsby-config.js文件中添加插件的设置。
plugins: [
...
{
resolve: 'gatsby-source-wordpress',
options: {
baseUrl: 'makoto-acu.com',
protocol: 'https',
hostingWPCOM: false, // wordpress.comにホスティングしている場合はtrue
useACF: false, // Advanced Custom Fieldsを使っている場合はtrue
includedRoutes: [
"**/categories",
"**/posts",
"**/pages",
"**/media",
"**/tags",
"**/taxonomies",
"**/users",
],
}
}
]
显示目录页
展示一覧页面非常简单。
我已经修改了pages/index.js如下。
重点在于查询部分,在这里我们使用GraphQL在构建时获取WordPress数据。
const IndexPage = ({data}) => (
<Layout>
<SEO title="Home"/>
<h1>Hello Gatsby</h1>
<h1>Posts</h1>
{data.allWordpressPost.edges.map(({node}) => (
<div key={node.slug}>
<Link to={node.slug} css={{textDecoration: `none`}}>
<h3>{node.title}</h3>
</Link>
<div dangerouslySetInnerHTML={{__html: node.excerpt}}/>
</div>
))}
</Layout>
)
export default IndexPage
export const query = graphql`
query {
allWordpressPost(sort: { fields: [date] }) {
edges {
node {
title
excerpt
slug
}
}
}
}
`
显示详细页面
詳細頁的顯示較為複雜,它會根據從API獲取的數據動態生成頁面。
首先,在gatsby-node.js中寫入以下內容。
在createPage()函數中,根據API的獲取結果,使用下面要提到的模板動態生成頁面。
const path = require('path')
const slash = require('slash')
exports.createPages = async ({ graphql, actions }) => {
const { createPage } = actions
const result = await graphql(`
{
allWordpressPost {
edges {
node {
id
title
status
}
}
}
}
`)
if (result.errors) {
throw new Error(result.errors)
}
const { allWordpressPost } = result.data
const postTemplate = path.resolve('./src/templates/post.js') // テンプレートのパス
allWordpressPost.edges.forEach(edge => {
createPage({
path: `/${edge.node.title}/`, // ページを紐付けるURL
component: slash(postTemplate), // もととなるページテンプレートを指定
context: {
id: edge.node.id, // templateにわたす変数
},
})
})
}
接下来,我们将创建用作生成页面基础的模板。
请在templates目录中创建一个新文件post.js,并按照以下内容进行添加。
关键点在于GraphQL部分,使用gatsby-node.js的createPage()函数接收的变量(页面ID)来进行查询。
这样我们就可以获取并显示每个页面的信息。
import React, { Component } from "react"
import { graphql } from "gatsby"
import PropTypes from "prop-types"
import Layout from "../components/layout"
class PostTemplate extends Component {
render() {
const post = this.props.data.wordpressPost
return (
<Layout>
<h1 dangerouslySetInnerHTML={{ __html: post.title }} />
<div dangerouslySetInnerHTML={{ __html: post.content }} />
</Layout>
)
}
}
PostTemplate.propTypes = {
data: PropTypes.object.isRequired,
edges: PropTypes.array,
}
export default PostTemplate
export const pageQuery = graphql`
query($id: String!) {
wordpressPost(id: { eq: $id }) {
title
content
}
}
`
最后
在以上,我們使用Gatsby.js與WordPress進行了整合。我們成功顯示了文章列表和詳細內容。因此,我認為Gatsby.js非常適合從WordPress遷移。由於它能輕鬆地利用WordPress資源。在進行開發的過程中,我們也將附帶整理其他的技巧。
赠品
如果你在IntelliJ中使用GraphQL,我推荐这个插件。它可以自动从端点生成schema.js,并让你流畅地编写查询。
这个插件在使用IntelliJ写GraphQL时非常方便。