首页 > 解决方案 > 在 GraphQL Wordpress 查询搜索中包含 mediaItems

问题描述

我有一个无头 WordPress 安装,并使用 React 前端通过以下搜索查询来查询帖子:

  posts(where: {search: $searchStr}) {
    nodes {
        title
        content
        link
    }
  }

但也想在搜索结果中包含媒体文件。我可以从以下附加查询中查询和注销 mediaItems:

  mediaItems {
    nodes {
      title
      sourceUrl
    }
  }

但无法弄清楚如何将这些包含在搜索结果中。如何在同一个搜索查询中组合postsandmediaItems并根据搜索字符串返回所有结果?

更新了完整的查询

我正在使用的完整查询将搜索查询传递到帖子 GraphQL 查询中。由于mediaItemsposts都是 WordPress 中的顶级,我如何结合这两个查询,以便根据搜索参数返回所有帖子和所有媒体项?

query appQuery($searchStr: String) {
  posts(where: {search: $searchStr}) {
    nodes {
        title
        content
        link
        tags{
          nodes {
            name
          }
        }
    }
  }
  mediaItems {
    nodes {
      title
      sourceUrl
    }
  }
}

标签: reactjswordpressgraphql

解决方案


您可以为此创建另一个 GraphQL 并将type其嵌套在您的 maintype中,以便您也可以查询您的数据。还要为要检索的数据添加解析器。

例如:假设您有一个博客网站并且您有一些帖子。为了那个原因

type Post {
  _id: String
  title: String
  credit: PostCredit # Name of nested type
}
type PostCredit {
  authorId: String # You can also perform further nesting
  publicationId: String
}

推荐阅读