循环当前定制帖子类型及其值的所有定制分类

时间:2013-02-19 作者:Lars van Peij

我想做什么:

我有四种自定义的帖子类型。我只想用一个,我可以这样做:$current_posttype = get_post_type( $post->ID ); // get current post type .

接下来,我想遍历附加到该自定义帖子类型的所有自定义分类法。例如:

custom post type: movies
custom taxonomy 1: genre
custom taxonomy 2: rating
custom taxonomy 3: year
and so on..
我想输出以下内容(针对当前帖子):

genre: Western
rating: 4
year: 2000
我所知道的是,我可以使用以下代码输出自定义分类法的所有术语。

// Get terms for post
 $terms = get_the_terms( $post->ID , \'genre\' );

 // Loop over each item since it\'s an array
 if ( $terms != null ){
    foreach( $terms as $term ) {
     // Print the name method from $term which is an OBJECT
 if ( $term->name != null ) {
 ?></br><?php print $term->name ;
 // Get rid of the other data stored in the object, since it\'s not needed
 }
 else {
 }
  unset($term);
} } 
我不知道的是如何使用foreach循环来循环这个问题。我想不出来。有什么帮助或建议吗?谢谢

2 个回复
SO网友:RRikesh

您可以循环检索分类法:

foreach( array(\'genre\', \'rating\', \'year\') as $taxo ){
  #loop over each taxonomy
  $terms = get_the_terms( $post->ID , $taxo );

  if( $terms && ! is_wp_error( $terms ) ){
    echo $taxo . \': \';
    $myterm = array();
    #get list of term names
    foreach($terms as $term){
      $myterm[] = $term->name;
    }

   #display comma separated list of terms
   echo implode(\',\', $myterm) . \'<br />\';
  }

}

Functions used:

get_the_terms(),implode()

SO网友:Matthew Boynes

听起来你要找的是get_object_taxonomies.

$taxonomies = get_object_taxonomies( $current_posttype );
foreach ( (array) $taxonomies as $taxonomy ) { 
    $terms = get_the_terms( $post->ID, $taxonomy );
    ...
}

结束

相关推荐