การ Query ข้อมูล WordPressCustom Posts
Custom Posts
อ่านเพิ่มเติมในคู่มือ การทำงานกับ Custom Posts
ต่อไปนี้คือตัวอย่าง queries สำหรับดึงข้อมูล custom post
CPT ที่ถูก map ไว้ใน schema
ดึง custom posts ด้วย 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 ที่ไม่ได้ถูก map ไว้ใน schema
ดึง custom posts สำหรับ CPT หลากหลายประเภท (ซึ่งต้องเปิดใช้งานให้ query ได้ผ่าน Settings):
query {
customPosts(
filter:{
customPostTypes: [
"page",
"nav_menu_item",
"wp_block",
"wp_global_styles"
]
}
) {
... on CustomPost {
id
title
customPostType
status
}
__typename
}
}การกรอง CPT ด้วย custom taxonomy
ดึง custom posts โดยกรองตาม category:
query {
customPosts(
filter: {
categories: {
includeBy: {
ids: [26, 28]
}
taxonomy: "product-cat"
}
}
) {
... on CustomPost {
id
title
}
... on GenericCustomPost {
categories(taxonomy: "product-cat") {
id
}
}
}
}การสร้าง custom posts
สำหรับการสร้าง CPT ที่ไม่ต้องการฟิลด์เพิ่มเติมนอกเหนือจากฟิลด์ใน Post คุณสามารถใช้ mutation createCustomPost ได้
query นี้สร้าง entry สำหรับ CPT "my-portfolio":
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
}
}
}
}การอัปเดต custom posts
query นี้อัปเดต title และ content สำหรับ CPT "my-portfolio":
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
}
}
}
}หรือใช้ nested mutations:
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
}
}
}
}
}