【问题标题】:How to query Wordpress relational fields with GraphQL?如何使用 GraphQL 查询 Wordpress 关系字段?
【发布时间】:2021-01-18 04:10:31
【问题描述】:

我在尝试使用 GraphQL 从 Wordpress 查询类型为“relationship”的自定义帖子类型时遇到问题

当我尝试查询这种类型为“post”的字段时,它只会导致此错误,并且会中断所有查询:

“消息”:“抽象类型 WpPostObjectUnion 必须在运行时为字段 WpPage_HomepageContent_heroSlider.buttonLink 解析为对象类型,其值为 { typename:“ActionMonitorAction”},收到“未定义”。WpPostObjectUnion 类型应提供“resolveType”函数或者每种可能的类型都应该提供一个“isTypeOf”函数。",

这是查询麻烦的部分:

query HomePageQuery {
  allWpPage(filter: {slug: {eq: "home"}}) {
    nodes {
      slug
      homepage_content {
        heroSlider {
          buttonText
          buttonLink {
            __typename
            ... on WpPost {
              id
            }
          }
        }
      }
    }
  }
}

你知道如何解决这个问题或做一些研究的方向吗?

谢谢!

【问题讨论】:

  • 使用 graphiql Playground 探索可能的类型/属性
  • 谢谢我这样做了。我终于找到了一个坏的和一个好的解决方案。见下文。

标签: reactjs wordpress graphql gatsby


【解决方案1】:

我找到了解决方案来获取我需要的“关系:链接到页面或文章”类型的 Acf 字段的数据,如下所示:

exports.createSchemaCustomization = ({ actions }) => {
  const { createTypes } = actions
  const typeDefs = `
      type WpPage_HomepageContent_heroSlider implements Node {
        buttonLink: WpPost
      }
    `
  createTypes(typeDefs)
}
exports.createResolvers = ({ createResolvers }) => {
  const resolvers = {
    Query: {
      allButtonLink: {
        type: ["WpPage_HomepageContent_heroSlider"],
        resolve(source, args, context, info) {
          return context.nodeModel.getAllNodes({ type: "ActionMonitorAction" })
        },
      },
    },
  }
  createResolvers(resolvers)
}

但这是一个繁重的解决方案,我认为这将涉及对这种类型的每个 Acf 字段执行相同的操作...

最佳解决方案:我最终决定将我们的 ACF 链接字段设置为键入“关系:链接”。 这种方式更简单,我不需要任何“createSchemaCustomization”或“createResolvers”解决方法来在 GraphQL 中的 buttonLink 字段中获取我的 slug,并且贡献者仍然可以轻松地在 Wordpress 后台选择文章。

buttonLink 现在返回我:

 "buttonLink": {
   "url": "/2020/09/04/article-test/",
   "target": "",
   "title": "Article test avec image en avant"
}

这就是我所需要的

【讨论】:

    猜你喜欢
    • 2017-06-20
    • 1970-01-01
    • 2020-12-04
    • 2019-10-30
    • 2019-03-02
    • 2018-02-07
    • 2019-02-10
    • 2017-09-27
    • 1970-01-01
    相关资源
    最近更新 更多