0

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.

1

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

0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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