0

I'm using the code below to show the featured image and link for the first post in each custom taxonomy for a custom post type. I'd like to display the name of the custom taxonomy next to each image, but despite best efforts I can't find the way to do this. I only want to show the current taxonomy that is being queried. Any ideas?

        $post_type = 'prints';

        // Get all the taxonomies for this post type
        $taxonomies = get_object_taxonomies( (object) array( 'post_type' => $post_type ) );

        foreach( $taxonomies as $taxonomy ) : 

            // Gets every "category" (term) in this taxonomy to get the respective posts
            $terms = get_terms( $taxonomy );

            foreach( $terms as $term ) : 

                $posts = new WP_Query( "taxonomy=$taxonomy&term=$term->slug&posts_per_page=1" );

                if( $posts->have_posts() ): while( $posts->have_posts() ) : $posts->the_post(); ?>
                    <div class="cat-preview">
                        <a href="<?php esc_url( the_permalink() ); ?>"><?php the_post_thumbnail ('medium'); ?></a>
                        <h2><!-- Looking to add custom taxonomy title here --></h2>
                    </div><?php
                endwhile; endif;

            endforeach;

        endforeach;
2
  • Do you mean name of taxonomy or term in taxonomy?
    – Rarst
    Sep 16, 2013 at 12:29
  • Sorry, yes, the name of the term in the taxonomy. G.M. has given a nice simple answer below which works perfectly. Sep 16, 2013 at 12:37

1 Answer 1

4

The name of the current taxonomy term is in the name property of the term object, so, in your loop just echo it:

if( $posts->have_posts() ): while( $posts->have_posts() ) : $posts->the_post(); ?>

<div class="cat-preview">
  <a href="<?php esc_url( the_permalink() ); ?>"><?php the_post_thumbnail ('medium'); ?></a>
  <h2><?php echo $term->name; ?></h2>
</div><?php endwhile; endif;
1
  • You are a legend. Perfectly simple when you know how. Thanks! Sep 16, 2013 at 12:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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