如何在WPGraphQL的Posts查询中获取Postmeta字段值?
解决WPGraphQL无法获取WordPress自定义字段的问题
- 注册自定义字段到WPGraphQL
WPGraphQL不会自动暴露所有自定义字段,必须手动注册。使用register_graphql_field函数完成注册,示例代码如下:
add_action( 'graphql_register_types', function() { register_graphql_field( 'Post', 'yourCustomFieldName', [ 'type' => 'String', // 根据字段实际类型调整,如Int、Boolean等 'description' => '自定义字段的描述信息', 'resolve' => function( $post ) { return get_post_meta( $post->ID, 'your_custom_field_key', true ); } ] ); } );
将代码中的yourCustomFieldName替换为你要查询的字段名,your_custom_field_key替换为PostMeta表中对应的元键。
- 检查ACF字段的GraphQL可见性
如果自定义字段是通过ACF(高级自定义字段)创建的,需在字段设置中开启「Show in GraphQL」选项;若通过代码注册ACF字段,需添加show_in_graphql和graphql_field_name参数:
acf_add_local_field_group( [ 'key' => 'group_123', 'title' => '自定义字段组', 'fields' => [ [ 'key' => 'field_456', 'name' => 'your_custom_field', 'type' => 'text', 'show_in_graphql' => true, 'graphql_field_name' => 'yourCustomField', ] ], 'location' => [ [ [ 'param' => 'post_type', 'operator' => '==', 'value' => 'post', ] ] ], ] );
清除缓存并重新查询
修改代码后,执行wp cache flush命令清除WordPress缓存,或在后台刷新缓存,之后重新执行GraphQL查询。验证查询语句的正确性
确保查询中的字段名与注册的字段名完全匹配,示例查询:
query { posts { nodes { id title yourCustomFieldName # 需与注册的字段名一致 } } }
内容的提问来源于stack exchange,提问作者Arun Pratap Singh
相关产品推荐
相关产品推荐

