【问题标题】:Do something If post has a term from a custom taxonomy做某事如果帖子有来自自定义分类的术语
【发布时间】:2018-04-09 16:21:31
【问题描述】:

我有一个自定义分类“库”,其中包含 2 个术语:“小说”和“小说”

我正在尝试根据我的帖子包含的此分类中的术语来执行功能。

所以如果帖子分配给“小说”,我需要//do something,如果帖子分配给“小说”,我需要//do something else

一开始,我一直在尝试使用is_tax,但这似乎没有按预期工作:

if ( is_tax('library','fiction' ) ) {   
    //do something
  } elseif ( is_tax('library','novels' ) ) {    
    //do something else
  }

我也尝试过has_term,但这对我也不起作用。

if ( has_term ('fiction','library' ) ) {    
        //do something
      } elseif ( has_term ('novels','libary' ) ) {  
        //do something else
      }

所以我想试试wp_get_post_terms,但我不确定如何执行这个。

我正在尝试这个:

$terms = wp_get_post_terms( $post->ID, 'library' );
foreach ( $terms as $term ) {
        if($term->name == 'fiction') {
            // do something
        }
        elseif($term->name == 'novels') {
            // do something else
        }
}

我错过了什么吗?特别是最后一个?

【问题讨论】:

    标签: php wordpress if-statement conditional custom-taxonomy


    【解决方案1】:

    通过使用 get_categories() 获取您的类别名称;功能

    $category_args = array(
        'type'                     => 'yourposttypename',
        'child_of'                 => 0,
        'parent'                   => 0,
        'orderby'                  => 'id',
        'order'                    => 'ASC',
        'hide_empty'               => 0,
        'hierarchical'             => 1,
        'exclude'                  => '',
        'include'                  => '',
        'number'                   => '',
        'taxonomy'                 => 'library',
        'pad_counts'               => false 
    
    ); 
    $categories = get_categories( $category_args );
    if(count($categories)>0)
    {
    
            foreach ( $categories as $category ) {
               if($category->name=='fiction')
               {
                    // do something
               }
               else  if($category->name=='novels')
               {
                    // do something else
               }
            }
    
    }
    

    【讨论】:

      猜你喜欢
      • 2018-01-08
      • 2016-07-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多