Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

What I want to do:

I have four custom post types. I only want to use one, which I can do like this: $current_posttype = get_post_type( $post->ID ); // get current post type .

Next up, I want to loop through all the custom taxonomies that are attached to that custom post type. So, for example:

custom post type: movies
custom taxonomy 1: genre
custom taxonomy 2: rating
custom taxonomy 3: year
and so on..

I want to output the following (for the current post):

genre: Western
rating: 4
year: 2000

What I do know is that I can use the following code to output all terms of a custom taxonomy.

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

What I don't know is how to loop over this, with a foreach loop. I can't figure it out. Any help or suggestions? Thanks.

share|improve this question
add comment

2 Answers

You can make a loop to retrieve the taxonomies:

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()

share|improve this answer
add comment

It sounds like what you're looking for is get_object_taxonomies.

$taxonomies = get_object_taxonomies( $current_posttype );
foreach ( (array) $taxonomies as $taxonomy ) { 
    $terms = get_the_terms( $post->ID, $taxonomy );
    ...
}
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.