LoginSignup
0
1

More than 1 year has passed since last update.

WPGraphQLを使って記事を表示させる方法

Last updated at Posted at 2021-11-14

インストール方法

wp-graphqlってゆう名前のプラグインをWPからインストールしてください。

ファイル内に記述する内容

ファイルインストール

import client from '@/apollo-client'
import Posts from '@/graphql/posts'

apolloのセッティング

import { ApolloClient, InMemoryCache } from "@apollo/client";

const client = new ApolloClient({
    uri: 'http://localhost/graphql', // WPのgraphql先になります。
    cache: new InMemoryCache(),
});

export default client;

Nextjsを使っていましたので、静的にページを生成するためにgetStaticPropsを使っています。

export const getStaticProps: GetStaticProps = async () => {
  const data: any = await client.query({
    query: Posts.items(),
    fetchPolicy: 'network-only',
  })

  return {
    props: {
      pictureListContents: data.data.posts.edges,
    },
  }
}

GraphQL

GraphQLのクエリ内容

import { gql } from '@apollo/client'

const gqlpost = {
  items: function () {
    return gql`
      query {
        posts {
          edges {
            node {
              id
              title
              excerpt
              date
              postId
              slug
              featuredImage {
                node {
                  uri
                  slug
                  sourceUrl
                }
              }
            }
          }
        }
      }
    `
  },

}
export default gqlpost

以上になります。
利用方法は至ってシンプルです。他にも使用方法はありますが、WPGraphQLに特化した内容ではなくなるのでこちらの記事では割愛します。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1