Go to list of users who liked
More than 5 years have passed since last update.
WorpdressからGatsby.jsに移行するにあったって、wordpressの記事情報の取得・表示までの連携をメモします。
以下内容はCLIにてgatsby new
で作成したプロジェクトを基本にしています。
Wordpressプラグインの追加
wrodpressとの連携は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にホスティングしている場合はtrueuseACF:false,// Advanced Custom Fieldsを使っている場合はtrueincludedRoutes:["**/categories","**/posts","**/pages","**/media","**/tags","**/taxonomies","**/users",],}}]
一覧ページの表示
一覧ページの表示は、とても簡単です。pages/index.js
を以下のように修正しました。
ポイントはquery
部分で、こちらにてビルド時にGraphQLでWordpressのデータを取得しています。
constIndexPage=({data})=>(<Layout><SEOtitle="Home"/><h1>Hello Gatsby</h1><h1>Posts</h1>{data.allWordpressPost.edges.map(({node})=>(<divkey={node.slug}><Linkto={node.slug}css={{textDecoration:`none`}}><h3>{node.title}</h3></Link><divdangerouslySetInnerHTML={{__html:node.excerpt}}/></div>))}</Layout>)exportdefaultIndexPageexportconstquery=graphql` query { allWordpressPost(sort: { fields: [date] }) { edges { node { title excerpt slug } } } }`
詳細ページの表示
詳細ページの表示は少し複雑で、APIから取得したデータを元にページを動的に生成します。
まず、gatsby-node.js
に以下を記述します。
こちらのcreatePage()
関数にてAPIの取得結果から後述するtemplateを元に動的にページを生成しています。
constpath=require('path')constslash=require('slash')exports.createPages=async({graphql,actions})=>{const{createPage}=actionsconstresult=awaitgraphql(` { allWordpressPost { edges { node { id title status } } } } `)if(result.errors){thrownewError(result.errors)}const{allWordpressPost}=result.dataconstpostTemplate=path.resolve('./src/templates/post.js')// テンプレートのパスallWordpressPost.edges.forEach(edge=>{createPage({path:`/${edge.node.title}/`,// ページを紐付けるURLcomponent:slash(postTemplate),// もととなるページテンプレートを指定context:{id:edge.node.id,// templateにわたす変数},})})}
続いて、生成ページの基礎となるtemplateを作成します。templates
ディレクトリを切りpost.js
を以下内容で新たに追加します。
ポイントはGraphQL部分でgatsby-node.js
のcreatepage()
で受け取った変数(ページID)を使って問い合わせを行っている点です。
これでページごとの情報を取得して表示しています。
importReact,{Component}from"react"import{graphql}from"gatsby"importPropTypesfrom"prop-types"importLayoutfrom"../components/layout"classPostTemplateextendsComponent{render(){constpost=this.props.data.wordpressPostreturn(<Layout><h1dangerouslySetInnerHTML={{__html:post.title}}/><divdangerouslySetInnerHTML={{__html:post.content}}/></Layout>)}}PostTemplate.propTypes={data:PropTypes.object.isRequired,edges:PropTypes.array,}exportdefaultPostTemplateexportconstpageQuery=graphql` query($id: String!) { wordpressPost(id: { eq: $id }) { title content } }`
終わりに
以上、Gatsby.jsでWordPressと連携。記事を一覧、詳細を表示するまででした。
このように簡単にwordpressのリソースを利用できるので、wordpressからの移行にgatsby.jsはとてもオススメだと思います。
色々開発進める中でのTipsを別途纏めていきたいと思います。
おまけ
拙著ですがIntelliJでGraphQL扱うなら、このPluginがオススメです。
エンドポイントからschema.jsを自動生成してくれて、流れるようにQuery書けます。
intelliJでgraphQLを書くときに便利なプラグイン
Register as a new user and use Qiita more conveniently
- You get articles that match your needs
- You can efficiently read back useful information
- You can use dark theme