WordPressデータのクエリ
WordPressデータのクエリカスタム投稿

カスタム投稿

詳細はガイド カスタム投稿を使った作業 をご参照ください。

以下は、カスタム投稿データを取得するクエリの例です。

スキーマにマッピングされたCPT

CPT "post""page" のカスタム投稿を取得します:

query {
  customPosts(filter: { customPostTypes: ["post", "page"] }) {
    ...CustomPostProps
    ...PostProps
    ...PageProps
  }
}
 
fragment CustomPostProps on CustomPost {
  __typename
  title
  excerpt
  url
  dateStr(format: "d/m/Y")
}
 
fragment PostProps on Post {
  tags {
    id
    name
  }
}
 
fragment PageProps on Page {
  author {
    id
    name
  }
}

スキーマにマッピングされていないCPT

さまざまなCPT(設定でクエリ可能に有効化する必要があります)のカスタム投稿を取得します:

query {
  customPosts(
    filter:{
      customPostTypes: [
        "page",
        "nav_menu_item",
        "wp_block",
        "wp_global_styles"
      ]
    }
  ) {
    ... on CustomPost {
      id
      title
      customPostType
      status
    }
    __typename
  }
}

カスタムタクソノミーによるCPTのフィルタリング

カテゴリーでフィルタリングしてカスタム投稿を取得します:

query {
  customPosts(
    filter: {
      categories: {
        includeBy: {
          ids: [26, 28]
        }
        taxonomy: "product-cat"
      }
    }
  ) {
    ... on CustomPost {
      id
      title
    }
    ... on GenericCustomPost {
      categories(taxonomy: "product-cat") {
        id
      }
    }
  }
}

カスタム投稿の作成

Post のフィールド以上の追加フィールドを必要としないCPTを作成するには、createCustomPost ミューテーションを使用できます。

このクエリは "my-portfolio" CPT のエントリを作成します:

mutation {
  createCustomPost(
    input: {
      customPostType: "my-portfolio"
      title: "My photograph"
      contentAs: { html: "This is my photo, check it out." }
    }
  ) {
    status
    errors {
      __typename
      ...on ErrorPayload {
        message
      }
      ...on GenericErrorPayload {
        code
      }
    }
    customPost {
      __typename
      ...on CustomPost {
        id
        title
        content
      }
    }
  }
}

カスタム投稿の更新

このクエリは "my-portfolio" CPT のタイトルとコンテンツを更新します:

mutation {
  updateCustomPost(input: {
    id: 1
    customPostType: "my-portfolio"
    title: "Updated title"
    contentAs: { html: "Updated content" }
  }) {
    status
    errors {
      __typename
      ...on ErrorPayload {
        message
      }
    }
    customPost {
      __typename
      ...on CustomPost {
        id
        title
        content
      }
    }
  }
}

またはネストされたミューテーションを使用する場合:

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