WordPress API:返回帖子及其类别
问题描述:
此函数查询所有帖子的WP API。但我很努力在这个回复中添加每个帖子所在的类别?WordPress 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;
}
+0
我用这个'catagory'=> array_column($ catagory,'name'),它返回这个,“catagory”:[“A Name”]。有什么办法可以将这个数组变成同一行中的刺痛吗?提前致谢! – realbadrabbits
+0
谢谢,作品像魅力:) – realbadrabbits
是很危险的人去!拿这个:https://developer.wordpress.org/reference/functions/get_the_category/ – WheatBeak
谢谢,但我将如何添加到我的功能?我是新来的:/ – realbadrabbits
'$ catarray = get_the_category($ post-> ID)'会给你一个属于这个帖子的类别对象数组。如果帖子有多个类别,你想要一个数组或字符串? – WheatBeak