[英]WordPress API: return posts with their categories
此函数查询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;
}
我认为这应该可以解决问题:
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.