查询插件数据Meta Box
Meta Box
与 Meta Box 插件数据进行交互的 Query 示例。
获取 Meta Box 自定义字段
我们可以使用元字段来查询 Meta Box 自定义字段的数据,无论其类型如何:
query GetPost($postId: ID!) {
post(by: { id: $postId }) {
id
title
text: metaValue(key: "text_field")
textarea: metaValue(key: "textarea_field")
select: metaValue(key: "select_field")
multiSelect: metaValues(key: "multi_select_field")
}
}如果元值是一种关联关系(例如:文章、用户、分类法等),我们可以使用该值来查询对应的 Post、User、Taxonomy 等类型的实体:
query GetPostWithRelationships($postId: ID!) {
post(by: { id: $postId }) {
id
title
# Export the relationship to a post
relationshipPostId: metaValue(key: "relationship_post_id")
@export(as: "relationshipPostId")
# Export the relationship to a list of posts
relationshipPostIds: metaValues(key: "relationship_post_ids")
@export(as: "relationshipPostIds")
}
}
query QueryPostRelationships @depends(on: "GetPostWithRelationships") {
# Query the relationship to a post
relationshipPost: post(by: { id: $relationshipPostId }) {
id
title
}
# Query the relationship to a list of posts
relationshipPosts: posts(filter: { ids: $relationshipPostIds }) {
id
title
}
}更新 Meta Box 自定义字段
我们可以使用元变更来更新 Meta Box 自定义字段的数据,通过传入字段名称和值,无论其类型如何:
mutation UpdatePost($postId: ID!) {
updatePost(
input: {
id: $postId
meta: {
text_field: ["New text value"],
textarea_field: ["New textarea value"],
select_field: ["New select value"],
multi_select_field: ["Choice 1", "Choice 2"],
}
}
) {
status
errors {
__typename
...on ErrorPayload {
message
}
}
post {
id
text: metaValue(key: "text_field")
textarea: metaValue(key: "textarea_field")
select: metaValue(key: "select_field")
multiSelect: metaValues(key: "multi_select_field")
}
}
}Prev