6
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Gatsby.jsでWordPressのAPIをGraphQLで取得しるときによく使うquery

Last updated at Posted at 2019-12-08

gatsby.jsのplugin「gatsby-source-wordpress」でWordPressが提供しているRestAPIをGraphQLで取得できるようになります。
そのよく使うqueryについてまとめました

※Headless CMS(WordPress)とGatsby.jsでサイト制作するの備忘録については別の記事としてまとめています。「Headless CMS(WordPress)とGatsby.jsでサイト制作する際の備忘録

GraphQLで取得したdataをcomponentのprops展開する方法

import React from 'react';
import { graphql, StaticQuery } from 'gatsby';

const Hoge = () => (
  <>
    <StaticQuery query={graphql`
      {
        allWordpressPage{
          edges{
            node{
              id
              title
              content
            }
          }
        }
      }
    `} render={props => (
      <>
        {props.allWordpressPage.edges.map(page => (
          <div key={page.node.id}>
            <h1>{page.node.title}</h1>
            <div dangerouslySetInnerHTML={{ __html: page.node.content }} />
          </div>
        ))}
      </>
    )} />
  </>
);

export default Hoge;

投稿ページ

{
  allWordpressPost{
    edges{
      node{
        wordpress_id
        title
        content
        excerpt
        date(formatString: "YYYY/MM/DD hh:mm")
      }
    }
  }
}

固定ページ

{
  allWordpressPage {
    edges {
      node {
        id
        slug
        status
        template
        title
        content
        template
      }
    }
  }
}

メニュー

{
  allWordpressWpApiMenusMenusItems(filter: {
    name: {
      eq: "Main menu"
    }
  }){
    edges{
      node{
        items{
          title
          object_slug
        }
      }
    }
  }
}

サイトタイトルとディスクリプション

{
  allWordpressSiteMetadata{
    edges{
      node{
        name
        description
      }
    }
  }
}

カスタム投稿タイプ「portfolio」

{
  allWordpressWpPortfolio{
    edges{
      node{
        id
        title
        slug
        excerpt
        content
        featured_media{
          source_url
        }
      }
    }
  }
}

Advanced Custom Fieldsのdataを取得

  • WordPressのプラグイン「Advanced Custom Fields」「ACF to REST API」をinstall
{
  allWordpressWpPortfolio{
    edges{
      node{
        title
        acf {
          portfolio_url
        }
      }
    }
  }
}
6
6
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
6
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?