WordPressデータのクエリ
WordPressデータのクエリ投稿

投稿

これらは投稿データを取得・変更するクエリの例です。

投稿の取得

著者とタグを含む単一の投稿:

query {
  post(by: { id: 1 }) {
    title
    content
    url
    date
    author {
      id
      name
    }
    tags {
      id
      name
    }
  }
}

コメントを含む5件の投稿一覧:

query {
  posts(pagination: { limit: 5 }) {
    id
    title
    excerpt
    url
    dateStr(format: "d/m/Y")
    comments(pagination: { limit: 5 }) {
      id
      date
      content
    }
  }
}

指定した投稿の一覧:

query {
  posts(filter: { ids: [1499, 1657] }) {
    id
    title
    excerpt
    url
    date
  }
}

投稿のフィルタリング:

query {
  posts(
    filter: { search: "wordpress", dateQuery: { after: "2019-06-01" } },
    sort: { order: ASC, by: TITLE }
  ) {
    id
    title
    excerpt
    url
    status
  }
}

投稿件数のカウント:

query {
  postCount(
    filter: { search: "api" }
  )
}

投稿のページネーション:

query {
  posts(
    pagination: {
      limit: 5,
      offset: 5
    }
  ) {
    id
    title
  }
}

タグを持つ投稿:

query {
  posts(
    filter: { tagSlugs: ["graphql", "wordpress", "plugin"] }
  ) {
    id
    title
  }
}

カテゴリーを持つ投稿:

query {
  posts(
    filter: { categoryIDs: [50, 190] }
  ) {
    id
    title
  }
}

メタ値の取得:

query {
  posts {
    title
    metaValue(
      key: "_wp_page_template",
    )
  }
}

ログイン中ユーザーの投稿の取得

postpostspostCount フィールドは、ステータスが "publish" の投稿のみを取得します。

ログイン中のユーザーの投稿を、任意のステータス("publish""pending""draft""trash")で取得するには、以下のフィールドを使用します:

  • myPost
  • myPosts
  • myPostCount
query {
  myPosts(filter: { status: [draft, pending] }) {
    id
    title
    status
  }
}

投稿の作成

ログイン中のユーザーのみが投稿を作成できます。

mutation {
  createPost(
    input: {
      title: "Hi there!"
      contentAs: { html: "How do you like it?" }
      status: draft
      tags: ["demo", "plugin"]
    }
  ) {
    status
    errors {
      __typename
      ...on ErrorPayload {
        message
      }
      ...on GenericErrorPayload {
        code
      }
    }
    postID
    post {
      status
      title
      content
      url
      date
      author {
        id
        name
      }
      tags {
        id
        name
      }
    }
  }
}

投稿の更新

対応する権限を持つユーザーのみが投稿を編集できます。

mutation {
  updatePost(
    input: {
      id: 1,
      title: "This is my new title",
    }
  ) {
    status
    errors {
      __typename
      ...on ErrorPayload {
        message
      }
      ...on GenericErrorPayload {
        code
      }
    }
    post {
      id
      title
    }
  }
}

このクエリはネストされたmutationを使用して投稿を更新します:

mutation {
  post(by: { id: 1 }) {
    originalTitle: title
    update(input: {
      title: "This is my new title",
      contentAs: { html: "This rocks!" }
    }) {
      status
      errors {
        __typename
        ...on ErrorPayload {
          message
        }
      }
      post {
        newTitle: title
        content
      }
    }
  }
}