Query examplesPosts
Posts
These are examples of queries to fetch and modify post data.
Fetching posts
A single post, with author and tags:
query {
post(by: { id: 1 }) {
title
content
url
date
author {
id
name
}
tags {
id
name
}
}
}
A list of 5 posts with their comments:
query {
posts(pagination: { limit: 5 }) {
id
title
excerpt
url
dateStr(format: "d/m/Y")
comments(pagination: { limit: 5 }) {
id
date
content
}
}
}
A list of predefined posts:
query {
posts(filter: { ids: [1499, 1657] }) {
id
title
excerpt
url
date
}
}
Filtering posts:
query {
posts(
filter: { search: "wordpress", dateQuery: { after: "2019-06-01" } },
sort: { order: ASC, by: TITLE }
) {
id
title
excerpt
url
status
}
}
Counting post results:
query {
postCount(
filter: { search: "api" }
)
}
Paginating posts:
query {
posts(
pagination: {
limit: 5,
offset: 5
}
) {
id
title
}
}
Posts with tags:
query {
posts(
filter: { tagSlugs: ["graphql", "wordpress", "plugin"] }
) {
id
title
}
}
Posts with categories:
query {
posts(
filter: { categoryIDs: [50, 190] }
) {
id
title
}
}
Fetching meta values:
query {
posts {
title
metaValue(
key: "_wp_page_template",
)
}
}
Fetching the logged-in user's posts
Fields post
, posts
and postCount
only retrieve posts with status "publish"
.
To fetch posts from the logged-in user, with any status ("publish"
, "pending"
, "draft"
or "trash"
), use these fields:
myPost
myPosts
myPostCount
query {
myPosts(filter: { status: [draft, pending] }) {
id
title
status
}
}
Creating posts
Only logged-in users can create posts.
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
}
}
}
}
Updating posts
Only users with the corresponding capabilities can edit posts.
mutation {
updatePost(
input: {
id: 1,
title: "This is my new title",
}
) {
status
errors {
__typename
...on ErrorPayload {
message
}
...on GenericErrorPayload {
code
}
}
post {
id
title
}
}
}
This query uses nested mutations to update the post:
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
}
}
}
}