如何将高级自定义字段分类字段添加到restAPI响应

时间:2019-10-21 10:29:38

标签: php wordpress wordpress-rest-api

我正在尝试构建一个可以快速加载大量数据的API。我需要显示标题,类别名称和类别图像。

我首先从ACF插件添加自定义字段,然后将其放入分类法中。我创建了一个新的rest API路由并创建了一个回调函数

function fetch_ideas ( $request_data ) {

    $page = $request_data['page'];
    // setup query argument

    $args = array(
        'post_type' => 'ideas_post_type',
        'order' => 'ASC',
        'posts_per_page' => 1,
        'paged'             => $page,
    );


    // get posts
    $posts = get_posts($args);
    // add custom field data to posts array so we can fetch it
    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);
            $posts[$key]->categories = get_the_category($post->ID);
            $posts[$key]->catimage = $posts[$key]->catimage = get_field('cat_image',  get_the_category($post->ID ));
    }
    //make a custom json output (choose from post object what to display)
    //return $post
    $post_data = array();
    $i = 1;
    foreach( $posts as $posts_list) {
        $post_id = $posts_list->ID;
        $post_title = $posts_list->post_title;
        $post_content = $posts_list->link;
        $post_acf = $posts_list->acf;
        $post_category = $posts_list->categories;
        $post_cat_image = $posts_list->catimage;
        $post_data[$i][ 'title' ] = $post_title;
        $post_data[$i][ 'content' ] = $post_content;
        $post_data[$i][ 'acf' ] = $post_acf;
        $post_data[$i][ 'categories' ] = $post_category;
        $post_data[$i][ 'catImage' ] = $post_cat_image;
        $i ++;
    }
}

然后我从catImage值中得到了null,而不是字段值(在本例中为图像URL链接)。

0 个答案:

没有答案