Adding a custom post type to the schema

The union type CustomPostUnion is used whenever an entity can return custom posts.

 type
`CustomPostUnion` type

The GraphQL API makes a clear distinction of when a custom post is a "custom post", and not directly a "post". For instance, a comment can be added to a post, but also to a page and to a CPT, hence type Comment has field customPost: CustomPostUnion! (instead of field post: Post!) to retrieve the entity where the comment was added.

 type
`Comment` type

Configuring the queryable custom posts permalink

The custom post types that can be queried must be explicitly configured in the Settings page, under section "Included custom post types":

Selecting the allowed Custom Post Types in the Settings
Selecting the allowed Custom Post Types in the Settings

Resolving CustomPostUnion to a single type instead permalink

If there is only one type added to CustomPostUnion, we can then have the fields that resolve to CustomPostUnion be instead resolved to that unique type instead:

Settings for Custom Posts
Settings for Custom Posts

For instance, if Post is the only type, field customPosts from type Root resolves to it directly:

 field resolves to  type
`customPosts` field resolves to `Post` type

Mapped and Unmapped CPTs permalink

There are CPTs (such as "post" and "page") which already have a corresponding GraphQL type in the schema (Post and Page), and these types are incorporated directly into CustomPostUnion.

For any CPT that has not been modeled in the schema (such as "attachment", "revision" or "nav_menu_item", or any CPT installed by any plugin), their data will be accessed via the GenericCustomPost type.

For instance, this query retrieves entries from multiple CPTS:

{
customPosts(
filter: {
customPostTypes: [
"post",
"page",
"attachment",
"nav_menu_item",
"custom_css",
"revision"
],
status: [
publish,
inherit,
auto_draft
]
}
) {
id
title
content
status
customPostType
__typename
}
}

Querying custom posts permalink

Because all Custom Posts implement interface CustomPost, we can retrieve data from CustomPostUnion using a fragment reference or an inline fragment:

{
comments {
id
date
content
customPost {
__typename
...on CustomPost {
id
title
url
}
}
}
}

If we know that the comment was added to a post, we can also query fields specific to the Post:

{
comments {
id
date
content
customPost {
__typename
...on CustomPost {
id
title
url
}
...on Post {
categoryNames
}
}
}
}