Query WordPress 数据
Query WordPress 数据文章

文章

以下是获取和修改文章数据的 Query 示例。

获取文章

包含作者和标签的单篇文章:

query {
  post(by: { id: 1 }) {
    title
    content
    url
    date
    author {
      id
      name
    }
    tags {
      id
      name
    }
  }
}

包含评论的 5 篇文章列表:

query {
  posts(pagination: { limit: 5 }) {
    id
    title
    excerpt
    url
    dateStr(format: "d/m/Y")
    comments(pagination: { limit: 5 }) {
      id
      date
      content
    }
  }
}

指定文章列表:

query {
  posts(filter: { ids: [1499, 1657] }) {
    id
    title
    excerpt
    url
    date
  }
}

筛选文章:

query {
  posts(
    filter: { search: "wordpress", dateQuery: { after: "2019-06-01" } },
    sort: { order: ASC, by: TITLE }
  ) {
    id
    title
    excerpt
    url
    status
  }
}

统计文章数量:

query {
  postCount(
    filter: { search: "api" }
  )
}

文章分页:

query {
  posts(
    pagination: {
      limit: 5,
      offset: 5
    }
  ) {
    id
    title
  }
}

按标签筛选文章:

query {
  posts(
    filter: { tagSlugs: ["graphql", "wordpress", "plugin"] }
  ) {
    id
    title
  }
}

按分类筛选文章:

query {
  posts(
    filter: { categoryIDs: [50, 190] }
  ) {
    id
    title
  }
}

获取元数据值:

query {
  posts {
    title
    metaValue(
      key: "_wp_page_template",
    )
  }
}

获取已登录用户的文章

postpostspostCount 字段仅获取状态为 "publish" 的文章。

若要获取已登录用户的文章(包含任意状态:"publish""pending""draft""trash"),请使用以下字段:

  • myPost
  • myPosts
  • myPostCount
query {
  myPosts(filter: { status: [draft, pending] }) {
    id
    title
    status
  }
}

创建文章

只有已登录用户才能创建文章。

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
      }
    }
  }
}

更新文章

只有拥有相应权限的用户才能编辑文章。

mutation {
  updatePost(
    input: {
      id: 1,
      title: "This is my new title",
    }
  ) {
    status
    errors {
      __typename
      ...on ErrorPayload {
        message
      }
      ...on GenericErrorPayload {
        code
      }
    }
    post {
      id
      title
    }
  }
}

此 Query 使用嵌套 mutation 更新文章:

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
      }
    }
  }
}