我使用http://github.com/jjgrainger/PostTypes/ 注册我的自定义帖子类型和ACF,将自定义字段添加到我的自定义帖子中,我想在我的wp json响应中包括每个帖子的所有注册字段,我执行以下操作
$options = [
\'supports\' => array(\'revisions\'),
\'has_archive\' => false,
\'show_in_rest\' => true,
\'rewrite\' => array(\'slug\' => __(\'teachers\', \'teachers\')),
\'capability_type\' => \'post\',
\'rest_base\' => \'teachers\',
\'query_var\' => true,
\'rest_controller_class\' => \'WP_REST_Posts_Controller\',
];
$teachers = new PostType(\'teacher\', $options);
$locations = new Taxonomy(\'location\');
$levels = new Taxonomy(\'level\');
$teachers->filters([\'first_name\', \'last_name\']);
$teachers->columns()->hide([\'title\', \'date\']);
$teachers->columns()->add([
\'first_name\' => __(\'First Name\'),
\'last_name\' => __(\'Last Name\'),
]);
$teachers->taxonomy(\'location\');
$teachers->taxonomy(\'level\');
$teachers->columns()->populate(\'first_name\', function ($column, $post_id) {
echo get_post_meta($post_id, \'first_name\')[0];
});
$teachers->columns()->populate(\'last_name\', function ($column, $post_id) {
echo get_post_meta($post_id, \'last_name\')[0];
});
$levels->columns()->add([
\'level\' => __(\'Level\'),
]);
$levels->register();
$locations->register();
$teachers->register();
但是在wp-json响应中,我没有任何自定义字段,在google添加以下过滤器后,我尝试了这些字段
function my_rest_prepare_post($data, $post, $request) {
dd($data);
$_data = $data->data;
$fields = get_fields($post->ID);
foreach ($fields as $key => $value){
$_data[$key] = get_field($key, $post->ID);
}
$data->data = $_data;
return $data;
}
add_filter("rest_prepare_teacher", \'my_rest_prepare_post\', 10, 3);
但在这种情况下,我犯了一个致命的错误
Fatal error</b>: Uncaught Error: Call to a member function get_links() on null in
如何在自定义post类型的wp json响应中反映所有相关的自定义字段值?
Update
我忘了提到,在wordpress的顶部,我使用了带有sage的wordplate,在跟踪之后
rest_prepare_{$post_type}
我达到这一点的方法,在我的情况下是有效的
add_filter("rest_prepare_teacher", function($post) {
$_data = $post->data;
$fields = get_fields($_data[\'id\']);
foreach ($fields as $key => $value){
$_data[$key] = get_field($key, $_data[\'id\']);
}
$post->data = $_data;
return $post;
});