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

WPGraphQL使用SLUG查询自定义文章类型无返回数据问题

解决方案

第一步:确认CPT的GraphQL配置正确

  • 若使用Custom Post Type UI注册CPT,进入WordPress后台 → 自定义文章类型UI → 编辑projects类型
  • 拉到页面底部的「WPGraphQL设置」区块,确认以下配置:
    • 在GraphQL中显示设为是(ID可正常查询说明此项配置正确)
    • GraphQL单个名称填写查询时用的根字段名,例如填project的话,单条查询的根字段就是project
    • GraphQL复数名称填写为projects即可
  • 若为手动代码注册CPT,确认注册参数包含以下配置:
    'show_in_graphql' => true,
    'graphql_single_name' => 'project',
    'graphql_plural_name' => 'projects',
    

第二步:确认查询语句语法正确

按照上述配置,正确的查询语句示例如下:

query GetSingleProjectBySlug {
  project(id: "替换为目标project的slug", idType: SLUG) {
    id
    title
    slug
    content
    # 其他需要返回的字段
  }
}

注意:idType的枚举值必须为全大写的SLUG,小写的slug会触发参数错误

第三步:添加钩子开启自定义类型Slug查询支持

WPGraphQL 1.3.10属于较早版本,默认仅对原生文章、页面等内置类型开启SLUG类型的查询支持,自定义文章类型需要手动添加过滤器开启支持,将以下代码添加到当前主题的functions.php文件或者自定义功能插件中即可:

add_filter( 'graphql_post_object_id_type_supported', function( $is_supported, $post_type, $id_type ) {
    // 为projects自定义文章类型开启SLUG查询支持
    if ( 'projects' === $post_type && 'slug' === strtolower( $id_type ) ) {
        return true;
    }
    return $is_supported;
}, 10, 3 );

可选排查点

完成上述配置后仍无法查询到数据可做以下检查:

  • 确认查询使用的slug确实存在于projects类型的文章中,且无重复slug
  • 进入WPGraphQL后台的GraphQL Playground,在Schema文档中搜索你配置的单个名称(例如project),确认参数列表中存在idType且枚举值包含SLUG

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 14:57:05