我试图找出自定义的帖子类型类别名称&类别ID。但我失败了在哪里是我的问题使用以下脚本。我找不到任何人能帮助我。
$args = array(
'post_type' => 'manual',
'posts_per_page' => -1,
'taxonomy' => 'manual_cat',
);
$posts = new WP_Query($args);
$usermanual = [];
if ($posts->have_posts()):
while ($posts->have_posts()): $posts->the_post();
$usermanual[] = array(
'ID' => get_the_ID(),
'title' => get_the_title(get_the_ID()),
'content' => get_post_field('post_content', get_the_ID()),
'slug' => get_post_field('post_name', get_the_ID()),
'Note' => get_field('_wp_footnotes', get_the_ID()),
'category' => get_post_field('cat_ID', get_the_ID()),
);
endwhile;
endif;
第一个get_post_field()
不返回分类post项。您应该使用get_the_terms()
你的循环应该像这样
$posts = new WP_Query($args);
if ($posts->have_posts()):
while ($posts->have_posts()): $posts->the_post();
$post_terms = get_the_terms(get_the_ID(),'manual_cat');
$usermanual[] = array(
'ID' => get_the_ID(),
'title' => get_the_title(get_the_ID()),
'content' => get_post_field('post_content', get_the_ID()),
'slug' => get_post_field('post_name', get_the_ID()),
'Note' => get_field('_wp_footnotes', get_the_ID()),
'category' => $post_terms
);
echo '<pre>';
print_r($usermanual); // Debug results
echo '</pre>';
endwhile;
endif;
你应该使用
$category = get_the_category()[0];
$usermanual[] = array(
'ID' => get_the_ID(),
'title' => get_the_title(get_the_ID()),
'content' => get_post_field('post_content', get_the_ID()),
'slug' => get_post_field('post_name', get_the_ID()),
'Note' => get_field('_wp_footnotes', get_the_ID()),
'category_name' => $category['name'],
'category_id' => $category['term_id']
);
这里假设只有一个类别。对于自定义分类法,使用get_the_terms()。