How to get the taxonomy values of a custom post type

user2091936 picture user2091936 · Mar 21, 2014 · Viewed 53.2k times · Source

I am creating a new template that will get all the custom post type (Case Studies) content, including the taxonomies values associated with it.

So far I got the following:

<section>
<h1><?php _e( 'posts', 'casestudies' ); ?></h1>
<?php get_template_part('loop'); ?>
<?php
$args = array('post_type' => 'casestudies', 'posts_per_page' => 3);
$query = new WP_Query($args);
while($query -> have_posts()) : $query -> the_post();
?>
<h2><?php the_title(); ?></h2>
<p>Meta: <?php the_meta(); ?></p>
<p>Excerpt: <?php the_excerpt(); ?></p>
<p>what_to_put_here_to_get_taxonomies_values????</p>
<?php endwhile; ?>

<?php get_template_part('pagination'); ?>
</section>

How do I get the taxonomy of it? I have tried multiple things but all seemed to fail and just getting more confused.

Answer

MikO picture MikO · Mar 21, 2014

Check this function: wp_get_post_terms()

Assuming your custom post type Case Study supports two taxonomies called country and subject, you can try something like this:

<?php $terms = wp_get_post_terms( $query->post->ID, array( 'country', 'subject' ) ); ?>
<?php foreach ( $terms as $term ) : ?>
<p><?php echo $term->taxonomy; ?>: <?php echo $term->name; ?></p>
<?php endforeach; ?>

Your output would be something like:

Country: United Kingdom
Subject: Biology
Subject: Chemistry
Subject: Neurology