在REST API中使用ACF的自定义帖子类型,我如何获取这些值?

时间:2018-09-26 作者:fefe

我使用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;
});

2 个回复
SO网友:Adrian Barbosa

我真的希望你处理好了这个问题。如果您不这样做,这对我来说很有用,因为有一种方法可以在functions.php 您必须添加下一个代码的文件:

//Custom acf endpoint;
function my_endpoint( $request_data ) {

    // setup query argument
    $args = array(
        \'post_type\' => \'my_post_type\',
        \'posts_per_page\' => -1
    );

    // get posts
    $posts = get_posts($args);

    // add custom field data to posts array 
    foreach ($posts as $key => $post) {
            $posts[$key]->acf = get_fields($post->ID);
            $posts[$key]->link = get_permalink($post->ID);
            $posts[$key]->image = get_the_post_thumbnail_url($post->ID);
    }
    return $posts;
}

// register the endpoint;
add_action( \'rest_api_init\', function () {
    register_rest_route( \'my_endpoint/v1\', \'/my_post_type/\', array(
        \'methods\' => \'GET\',
        \'callback\' => \'my_endpoint\',
        )
    );
}
学分授予:https://clarencepearson.com/advanced-custom-fields-rest-api/

SO网友:virtualLast

这个答案激发了我的灵感,让我找到了自己的解决方案——我想把它贴在这里,以防将来对某人有所帮助:

use WP_Post;
use WP_REST_Request;
use WP_REST_Response;

class PreparePostAcfData
{
    public function preparePostAcfData(WP_REST_Response $response, WP_Post $post, WP_REST_Request $request): WP_REST_Response
    {
        $data = $response->get_data();
        $fieldsData = get_fields($post->ID);
        if(is_array($data[\'acf\']) && is_array($fieldsData)) {
            $data[\'acf\'] = array_merge($data[\'acf\'], $fieldsData);
        }
        $response->set_data($data);

        return $response;
    }
}
然后,您可以使用wordpress rest api过滤器之一将其附加到任何自定义帖子类型

$this->loader->add_filter(\'rest_prepare_advice_zone\', $plugin_public->preparePostAcfData, \'preparePostAcfData\', 99, 3);
唯一需要注意的是,我已经做好了定义$data[\'acf\'] 在请求周期的早期,您可以很容易地交换数组检查,以确定是否存在或任何相关的内容。阅读正在使用的wordpress过滤器rest_prepare_POST_TYPE

干杯

结束

相关推荐

Php致命错误:无法将WP_REST_RESPONSE类型的对象用作wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php中

我向WordPress添加了一个自定义端点,如下所示: add_action( \'rest_api_init\', function () { register_rest_route( \'menc/v1\', \'/crosscat/(?P[\\w-]+)/(?P[\\w-]+)\', array( \'methods\' => \'GET\', \'callback\' => \'dept_cat_api\',&#x

在REST API中使用ACF的自定义帖子类型,我如何获取这些值? - 小码农CODE - 行之有效找到问题解决它

在REST API中使用ACF的自定义帖子类型,我如何获取这些值?

时间:2018-09-26 作者:fefe

我使用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;
});

2 个回复
SO网友:Adrian Barbosa

我真的希望你处理好了这个问题。如果您不这样做,这对我来说很有用,因为有一种方法可以在functions.php 您必须添加下一个代码的文件:

//Custom acf endpoint;
function my_endpoint( $request_data ) {

    // setup query argument
    $args = array(
        \'post_type\' => \'my_post_type\',
        \'posts_per_page\' => -1
    );

    // get posts
    $posts = get_posts($args);

    // add custom field data to posts array 
    foreach ($posts as $key => $post) {
            $posts[$key]->acf = get_fields($post->ID);
            $posts[$key]->link = get_permalink($post->ID);
            $posts[$key]->image = get_the_post_thumbnail_url($post->ID);
    }
    return $posts;
}

// register the endpoint;
add_action( \'rest_api_init\', function () {
    register_rest_route( \'my_endpoint/v1\', \'/my_post_type/\', array(
        \'methods\' => \'GET\',
        \'callback\' => \'my_endpoint\',
        )
    );
}
学分授予:https://clarencepearson.com/advanced-custom-fields-rest-api/

SO网友:virtualLast

这个答案激发了我的灵感,让我找到了自己的解决方案——我想把它贴在这里,以防将来对某人有所帮助:

use WP_Post;
use WP_REST_Request;
use WP_REST_Response;

class PreparePostAcfData
{
    public function preparePostAcfData(WP_REST_Response $response, WP_Post $post, WP_REST_Request $request): WP_REST_Response
    {
        $data = $response->get_data();
        $fieldsData = get_fields($post->ID);
        if(is_array($data[\'acf\']) && is_array($fieldsData)) {
            $data[\'acf\'] = array_merge($data[\'acf\'], $fieldsData);
        }
        $response->set_data($data);

        return $response;
    }
}
然后,您可以使用wordpress rest api过滤器之一将其附加到任何自定义帖子类型

$this->loader->add_filter(\'rest_prepare_advice_zone\', $plugin_public->preparePostAcfData, \'preparePostAcfData\', 99, 3);
唯一需要注意的是,我已经做好了定义$data[\'acf\'] 在请求周期的早期,您可以很容易地交换数组检查,以确定是否存在或任何相关的内容。阅读正在使用的wordpress过滤器rest_prepare_POST_TYPE

干杯