发布对象显示术语名称

问题描述

如何显示链接到发布对象(ACF)的帖子的术语名称?

使用此代码,我可以看到该帖子的标题:

print(df1)
  C1  _max
0  x     0
1  x     1
5  y     5

解决方法

要获取帖子的术语名称,可以使用以下任一功能:

  1. wp_get_post_terms
  2. get_the_terms

它们的工作方式相同,但参数列表略有不同,更重要的是,get_the_terms对缓存的数据有效(使其更快),而wp_get_post_terms则不适用。

$postObj = get_field('which_game');

// DEPENDING ON WHICH FUNCTION YOU WANT TO USE:
$terms = get_the_terms( $postObj->ID,'provider');
// OR 
$terms = wp_get_post_terms( $postObj->ID,'provider' array( 'fields' => 'name') );

// Both functions return arrays,even if there is just 1 term
// so loop through the terms returned to add the names to an array
foreach ($terms as $term) 
    $term_names[] = $term->name;

// turn the array into a comma-separated string (of just the name on its own if there is just 1)
$term_name_str =  implode("','",$term_names);

如果确定只有1个学期,则可以检查是否返回了任何结果,然后得到第一个结果:

if (count($terms) > 1) 
    $term_name_str = $terms[0]->name;

但是,第一个示例仅适用于一个术语,而且更灵活。

注意-此代码未经测试,因此可能会有一些语法错误,但是基本概念是正确的。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...