You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

指定Post ID获取单篇文章Cursor却返回全部——WPGraphQL问题

问题原因及解决方案

问题出在变量名称不匹配:

  • 你的GraphQL查询定义的变量是$id,但在useQuery中传递的变量键是postId,导致查询中的where: {id: $id}没有获取到有效值,过滤器失效,最终返回所有文章的cursor。

修复代码

修改React部分的变量传递,将postId对应到查询中的id变量:

let postId = 138
const postCursor = useQuery(GET_POST_CURSOR, {variables: {id: postId}}) 
  
if (!postCursor.loading) { 
  console.log("cursor: ", postCursor)
}

另外,建议在查询中给变量添加非空约束(如果业务逻辑中ID必填),避免类似未传值的问题:

export const GET_POST_CURSOR = gql `
  query GetPostById($id: Int!) {
    posts(where: {id: $id}) {
      edges {
        cursor
      }
    }
  }
`;

这样修改后,查询会正确根据指定的id筛选对应的文章,返回其cursor。

内容的提问来源于stack exchange,提问作者sash

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 18:52:06