如何获取当前帖子分类法的术语名称



我正试图从分类法floorplanarea中获取当前帖子的术语名称。我想显示术语名称,然后输出该术语下的所有帖子有人能帮我吗?

<?php 
$floorplan_area = get_sub_field('floorplan_area');
if ($floorplan_area) {
if (!is_array($floorplan_area)) {
$floorplan_area = array($floorplan_area);
}
$args = array(
'post_type' => 'floorplan',
'posts_per_page' => -1,
'orderby' => 'post_title',
'order' => 'ASC',
'tax_query' => array(
array(
'taxonomy' => 'floorplanarea',
'terms' => $floorplan_area,
),
),
);
$area_query = new WP_Query($args);
if ($area_query->have_posts()) {?>
/*Title of term name to go here*/
<div>
<?php 
while($area_query->have_posts()) {
$area_query->the_post(); ?>
<h1><?php echo the_title(); ?></h1>
<?php } ?>
</div>
<?php 
}
wp_reset_postdata();
}
?>

找到解决方案

$term = get_term( $floorplan_area, 'floorplanarea' );
$name = $term->name;
echo $name;

一个WP_Term对象

object(WP_Term) (11) {
["term_id"]=>  //int
["name"]=>   //string 
["slug"]=>  //string 
["term_group"]=>  //int
["term_taxonomy_id"]=> //int
["taxonomy"]=>   //string
["description"]=>    //string
["parent"]=> //int
["count"]=>  // int
["filter"]= //string
["meta"]= array(0) {} //an array of meta fields.
}

由于它是一个对象,您需要使用foreach循环

$terms = get_terms($taxonomy);
foreach ($terms as $term) {
echo $term->name;
echo $term->slug;

$name = $term->name;
echo 'My name is:' . $name . '!';

}

最新更新