Php 从多个选定术语中获取单个分类术语
我在分类术语方面面临着有点复杂的情况。我有一个分类术语列表Php 从多个选定术语中获取单个分类术语,php,wordpress,taxonomy,Php,Wordpress,Taxonomy,我在分类术语方面面临着有点复杂的情况。我有一个分类术语列表 Taxonomy (property-status): --2018 --2019 --2020 --2021 --Coming Soon 我的分类法有多个术语,通常我从分类法中选择一个术语来显示我使用以下代码获取的术语: $status_terms = wp_get_post_terms( get_the_ID(), 'property-status'); if($status_terms) { foreach ( $sta
Taxonomy (property-status):
--2018
--2019
--2020
--2021
--Coming Soon
我的分类法有多个术语,通常我从分类法中选择一个术语来显示我使用以下代码获取的术语:
$status_terms = wp_get_post_terms( get_the_ID(), 'property-status');
if($status_terms) {
foreach ( $status_terms as $term ) {
echo $term->name;
}
}
这对我来说非常合适,但现在我选择了两个分类术语
2019
和即将推出
。如果选择了这两个选项,我只想显示2019
我不想在2019
旁边显示即将推出
,但是如果选择了即将推出
,那么我想显示即将推出。您可以计算术语并相应地过滤它们。这可能有点过于冗长,但可能会起到以下作用:
$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;
}
}
}
数一数术语的数量,检查其中是否有
即将到来
?@msg您能进一步解释一下吗,或者如果可能的话,给我看一下代码吗?您的代码正在为多个选定的术语使用即将到来
,但如果选择了“仅即将到来”,则不会显示任何内容。@SajjadAhmad-oops,计数中缺少括号
。更新的回答你太棒了@msg。现在很有魅力。这里缺少一个分号,我自己加上<代码>返回$term->名称代码>但我不想因此获得积分;)@SajjadAhmad谢谢你的提醒。再次更新答案。@SajjadAhmad替代解决方案,如果您感兴趣。