【问题标题】:get single taxonomy term from multiple selected terms从多个选定的术语中获取单个分类术语
【发布时间】:2018-10-04 08:15:40
【问题描述】:

我的分类术语有点复杂。我有分类术语列表。

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;
    }
}

这对我来说是完美的,但现在我选择了两个分类术语 2019coming soon。如果两者都被选中,我只想显示2019 我不想在2019 旁边显示coming soon,但如果只选择coming soon,那么我想很快就会显示。

【问题讨论】:

  • 算一下词条数,看看coming-soon是否在里面?
  • @msg 你能否进一步解释一下,或者如果可能的话给我看看代码?

标签: php wordpress taxonomy


【解决方案1】:

您可以计算术语并相应地过滤它们。这可能有点过于冗长,但可以解决问题:

$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;
    }
  }
}   

【讨论】:

  • 您的代码正在使用coming-soon 处理多个选定的术语,但如果只选择了coming-soon,它不会显示任何内容。
  • @SajjadAhmad 哎呀,count 上缺少括号。更新答案
  • 你太棒了@msg。现在就像一个魅力。这里缺少一件事分号,这是我自己添加的。 return $term->name; 但我不想为此获得荣誉;)
  • @SajjadAhmad 感谢您的提醒。再次更新答案。
  • @SajjadAhmad 有兴趣的替代解决方案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-25
  • 2018-04-20
  • 2016-07-01
  • 1970-01-01
相关资源
最近更新 更多