Search code examples
phpwordpresswordpress-rest-api

WordPress API: return posts with their categories


This function queries the WP API for all posts. But I am struggling to add to this response the categories that each post is in?

Ideally I would like to be returned in the same $data object as the post.

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;

}

Solution

  • I think this should do the trick:

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