将 ACF 添加到 CUSTOM wp api 端点

Adding ACF to CUSTOM wp api endpoints

我正在为 WP API 编写自定义端点,以检索来自 wordpress 的帖子,例如来自 'real_estate' post_type 和“5 人或更多”人的容量.

我构建了一个新的自定义端点:

// permite que meta_key e meta_value 
// sejam filtrados pela api
function filtros( $valid_vars ) {
    $valid_vars = array_merge( 
        $valid_vars, 
            array( 
                'meta_key', 
                'meta_value' ) );
    return $valid_vars;
}
add_filter( 'rest_query_vars', 'filtros' );
// funcção que retorna posts do autor
function busca( $data ) {
    $posts = get_posts(array(
        'post_type' => 'imoveis',
        'posts_per_page'    =>  '1000',
        'meta_query'    => array(
            'relation'  =>  'AND',
            array(
                'key'   =>  'transacao',
                'value' => $data['tipo']
            ),
            array(
                'key'   =>  'quartos',
                'value' => $data['quartos'],
                'compare'   =>  '>'
            )
        )
    ));

    if ( empty( $posts ) ) {
        return new WP_Error( 'sem resultados', 'quartos: ' . $data['quartos'] . ' transacao: '. $data['tipo'], array( 'status' => 404 ) );
    }
    return $posts;
}
// cria o endpoint que ira receber a função acima
add_action( 'rest_api_init', function () {
    register_rest_route( 'busca/v2', '/resultado/(?P<tipo>.+)/(?P<quartos>\d+)', 
        array(
            'methods' => 'GET',
            'callback' => 'busca',

        ) 
    );
});

搜索很好,有效,我正在按交易类型(出售或出租)和每个房地产中的房间数量进行过滤。

但是我的 JSON 回复缺少很多字段,包括 ACF。 前任: {
"ID":149, "post_author":"2", "post_date":"2016-03-03 23:53:39", "post_date_gmt":"2016-03-03 23:53:39", "post_content":"", "post_title":"Oportunidade do Ano", "post_excerpt":"", "post_status":"publish", "comment_status":"closed", "ping_status":"closed", "post_password":"", "post_name":"oportunidade-do-ano", "to_ping":"", "pinged":"", "post_modified":"2016-03-03 23:53:39", "post_modified_gmt":"2016-03-03 23:53:39", "post_content_filtered":"", "post_parent":0, "guid":"http://raphaelk.co/api/?post_type=imoveis&p=149", "menu_order":0, "post_type":"imoveis", "post_mime_type":"", "comment_count":"0", "filter":"raw" },

你们知道我该如何更改该回复吗?并包含 ACF。

谢谢

您是否尝试过简单地使用 ACF 函数 get_fields

在您的 "busca" 函数中,在 get_posts() 之后,如果 $posts 不为空,则像这样检索每个帖子的 acf 字段:

if ( empty( $posts ) ) {
  return new WP_Error( 'sem resultados', 'quartos: ' . $data['quartos'] . ' transacao: '. $data['tipo'], array( 'status' => 404 ) );
} else {
    foreach ($posts as $key => $post) {
        $posts[$key]->acf = get_fields($post->ID);
    }
}

希望就这样吧!