WordPress API:return 个帖子及其类别

WordPress API: return posts with their categories

此函数查询 WP API 的所有 post。但我正在努力将每个 post 所属的类别添加到此响应中?

理想情况下,我希望在与 post.

相同的 $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;

}

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

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;
}