简体   繁体   English

WordPress API:返回帖子及其类别

[英]WordPress API: return posts with their categories

This function queries the WP API for all posts. 此函数查询WP API的所有帖子。 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. 理想情况下,我希望在与帖子相同的$ 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;

}

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM