Query WordPress 数据自定义文章
自定义文章
详情请参阅指南 使用自定义文章。
以下是用于获取自定义文章数据的 Query 示例。
已映射到 Schema 的 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
}
}未映射到 Schema 的 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 mutation。
此 Query 为 "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
}
}
}
}更新自定义文章
此 Query 更新 "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:
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
}
}
}
}
}