WordPress API:返回其类别为

时间:2017-07-26 18:41:17

标签: php wordpress wordpress-rest-api

此函数在WP API中查询所有帖子。但是我很难在每个帖子的类别中添加这个回复吗?

理想情况下,我希望在与帖子相同的$ data对象中返回。

function getPosts($data) {

    $postType = $data['posttype'];
    $data = (object)[];

    $query = new WP_Query( array(
        'post_status' => 'publish',
        'order' => 'asc',
       'nopaging' => true
    ));

    foreach ($query->posts as $post) {
        $slug = $post->post_name;
        $item = array(
            'id' => $post->ID,
            'title' => $post->post_title,
            'slug' => $slug,
            'acf' => get_fields($post->ID),
        );
        $data->{$slug} = $item;
    }

    return $data;

}

1 个答案:

答案 0 :(得分:1)

我认为这应该可以解决问题:

foreach ($query->posts as $post) {
    $slug = $post->post_name;

    $catarray = array();
    $cats = get_the_category($post-ID);
    if(!empty($cats)){
        foreach($cats as $cat){
            $catarray[] = $cat->name;
        }
    }
    $catstring = implode(",", $catarray)

    $item = array(
        'id' => $post->ID,
        'title' => $post->post_title,
        'slug' => $slug,
        'acf' => get_fields($post->ID),
        'cats' => $catstring,
    );
    $data->{$slug} = $item;
}