Adding a custom post type to the schema
The union type CustomPostUnion
is used whenever an entity can return custom posts.
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.
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":
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:
For instance, if Post
is the only type, field customPosts
from type Root
resolves to it directly:
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
}
}
}
}