通过WP REST API创建文章时自定义字段不生效,求排查方案
问题排查与解决步骤
1. 替换register_meta中的占位符
你注册元字段时,第一个参数用了'POST_TYPE'占位符,必须替换为实际的自定义文章类型slug(比如你的自定义文章类型叫product,就写'product')。修正后的代码示例:
add_action( 'init', 'register_meta_function' ); function register_meta_function() { $meta_args = array( 'type' => 'string', 'description' => 'test', 'single' => true, 'show_in_rest' => true, ); // 替换为你实际的自定义文章类型slug register_meta( 'your-custom-post-type-slug', 'test', $meta_args ); }
2. 确认自定义文章类型支持REST API
注册自定义文章类型时,必须开启'show_in_rest' => true,否则REST API无法处理它的元字段。示例代码:
function register_custom_post_type() { $args = array( 'public' => true, 'label' => '自定义文章类型', 'show_in_rest' => true, // 必须开启该选项 // 其他配置参数... ); register_post_type( 'your-custom-post-type-slug', $args ); } add_action( 'init', 'register_custom_post_type' );
3. 检查API端点URL是否正确
创建自定义文章类型的API端点格式应为:https://你的域名/wp-json/wp/v2/你的自定义文章类型slug
确保$url变量指向这个正确地址,而非默认的普通文章端点(/wp-json/wp/v2/posts)。
4. 查看API返回结果排查错误
打印$result变量可以查看API返回的具体错误信息,帮助定位问题:
var_dump(json_decode($result, true));
如果存在权限不足、字段未注册等问题,返回结果会明确提示。
5. 验证用户权限(可选)
确保你使用的USER:PASSWORD对应的WordPress用户,拥有编辑该自定义文章类型的权限,且未被权限插件限制元字段的编辑权限。
内容的提问来源于stack exchange,提问作者composersucks
相关产品推荐
相关产品推荐

