从多个选定术语中获取单个分类术语
get single taxonomy term from multiple selected terms
我的分类术语有点复杂。我有分类术语列表。
Taxonomy (property-status):
--2018
--2019
--2020
--2021
--Coming Soon
我的分类法有多个术语,通常我 select 分类法中的一个术语要显示,我使用此代码获得:
$status_terms = wp_get_post_terms( get_the_ID(), 'property-status');
if($status_terms) {
foreach ( $status_terms as $term ) {
echo $term->name;
}
}
这对我来说很完美,但现在我 select 编辑了两个分类术语 2019
和 coming soon
。如果两者都是 selected 我只想显示 2019
我不想在 2019
旁边显示 coming soon
但如果只有 coming soon
是 selected 然后我想展示即将推出。
您可以计算术语并相应地过滤它们。这可能有点过于冗长,但可以解决问题:
$status_terms = wp_get_post_terms( get_the_ID(), 'property-status');
if($status_terms) {
// Get the term names only
$term_names = array_map(function($term) { return $term->name; }, $status_terms);
if ((count($term_names) > 1) && in_array('coming-soon', $term_names)) {
// More than one term and coming-soon. Filter it out
foreach ( $status_terms as $term ) {
if ($term->name != 'coming-soon') {
echo $term->name;
}
}
} else {
// Show everything
foreach ( $status_terms as $term ) {
echo $term->name;
}
}
}
较短的解决方案:
if($status_terms) {
$many_terms = (count($status_terms) > 1);
foreach ( $status_terms as $term ) {
if ($many_terms) {
if ($term->name != 'coming-soon') {
echo $term->name;
}
} else {
echo $term->name;
}
}
}
我的分类术语有点复杂。我有分类术语列表。
Taxonomy (property-status):
--2018
--2019
--2020
--2021
--Coming Soon
我的分类法有多个术语,通常我 select 分类法中的一个术语要显示,我使用此代码获得:
$status_terms = wp_get_post_terms( get_the_ID(), 'property-status');
if($status_terms) {
foreach ( $status_terms as $term ) {
echo $term->name;
}
}
这对我来说很完美,但现在我 select 编辑了两个分类术语 2019
和 coming soon
。如果两者都是 selected 我只想显示 2019
我不想在 2019
旁边显示 coming soon
但如果只有 coming soon
是 selected 然后我想展示即将推出。
您可以计算术语并相应地过滤它们。这可能有点过于冗长,但可以解决问题:
$status_terms = wp_get_post_terms( get_the_ID(), 'property-status');
if($status_terms) {
// Get the term names only
$term_names = array_map(function($term) { return $term->name; }, $status_terms);
if ((count($term_names) > 1) && in_array('coming-soon', $term_names)) {
// More than one term and coming-soon. Filter it out
foreach ( $status_terms as $term ) {
if ($term->name != 'coming-soon') {
echo $term->name;
}
}
} else {
// Show everything
foreach ( $status_terms as $term ) {
echo $term->name;
}
}
}
较短的解决方案:
if($status_terms) {
$many_terms = (count($status_terms) > 1);
foreach ( $status_terms as $term ) {
if ($many_terms) {
if ($term->name != 'coming-soon') {
echo $term->name;
}
} else {
echo $term->name;
}
}
}