Truy vấn dữ liệu WordPressBài viết
Bài viết
Đây là các ví dụ về queries để lấy và chỉnh sửa dữ liệu bài viết.
Lấy bài viết
Một bài viết đơn lẻ, kèm tác giả và thẻ:
query {
post(by: { id: 1 }) {
title
content
url
date
author {
id
name
}
tags {
id
name
}
}
}Danh sách 5 bài viết kèm bình luận:
query {
posts(pagination: { limit: 5 }) {
id
title
excerpt
url
dateStr(format: "d/m/Y")
comments(pagination: { limit: 5 }) {
id
date
content
}
}
}Danh sách các bài viết được chỉ định sẵn:
query {
posts(filter: { ids: [1499, 1657] }) {
id
title
excerpt
url
date
}
}Lọc bài viết:
query {
posts(
filter: { search: "wordpress", dateQuery: { after: "2019-06-01" } },
sort: { order: ASC, by: TITLE }
) {
id
title
excerpt
url
status
}
}Đếm số lượng bài viết:
query {
postCount(
filter: { search: "api" }
)
}Phân trang bài viết:
query {
posts(
pagination: {
limit: 5,
offset: 5
}
) {
id
title
}
}Bài viết theo thẻ:
query {
posts(
filter: { tagSlugs: ["graphql", "wordpress", "plugin"] }
) {
id
title
}
}Bài viết theo danh mục:
query {
posts(
filter: { categoryIDs: [50, 190] }
) {
id
title
}
}Lấy giá trị meta:
query {
posts {
title
metaValue(
key: "_wp_page_template",
)
}
}Lấy bài viết của người dùng đang đăng nhập
Các trường post, posts và postCount chỉ lấy các bài viết có trạng thái "publish".
Để lấy bài viết của người dùng đang đăng nhập với bất kỳ trạng thái nào ("publish", "pending", "draft" hoặc "trash"), hãy sử dụng các trường sau:
myPostmyPostsmyPostCount
query {
myPosts(filter: { status: [draft, pending] }) {
id
title
status
}
}Tạo bài viết
Chỉ người dùng đã đăng nhập mới có thể tạo bài viết.
mutation {
createPost(
input: {
title: "Hi there!"
contentAs: { html: "How do you like it?" }
status: draft
tags: ["demo", "plugin"]
}
) {
status
errors {
__typename
...on ErrorPayload {
message
}
...on GenericErrorPayload {
code
}
}
postID
post {
status
title
content
url
date
author {
id
name
}
tags {
id
name
}
}
}
}Cập nhật bài viết
Chỉ người dùng có quyền hạn tương ứng mới có thể chỉnh sửa bài viết.
mutation {
updatePost(
input: {
id: 1,
title: "This is my new title",
}
) {
status
errors {
__typename
...on ErrorPayload {
message
}
...on GenericErrorPayload {
code
}
}
post {
id
title
}
}
}Query này sử dụng nested mutations để cập nhật bài viết:
mutation {
post(by: { id: 1 }) {
originalTitle: title
update(input: {
title: "This is my new title",
contentAs: { html: "This rocks!" }
}) {
status
errors {
__typename
...on ErrorPayload {
message
}
}
post {
newTitle: title
content
}
}
}
}