List posts by taxonomy

List custom post types by taxonomy term.
List Posts For Terms Of A Custom Taxonomy For Any Post Type

I used this on a client website to list posts tagged by year.

Ie:
1940
-post 1
-post 2
1941
-post 3
-post 4…

I scoured the internet for a good working solution and there are so many that don’t work, this this simply did. Cut n paste. Originally written by nickam.



<?php
$post_type = 'filmography';
$tax = 'film-year';
$tax_terms = get_terms($tax,'hide_empty=0');

//list the taxonomy
$i=0; // counter for printing separator bars
foreach ($tax_terms as $tax_term) {
$wpq = array ('taxonomy'=>$tax,'term'=>$tax_term->slug);
$query = new WP_Query ($wpq);
$article_count = $query->post_count;
echo "<a href=\"#".$tax_term->slug."\">".$tax_term->name."</a>";
// output separator bar if not last item in list
if ( $i < count($tax_terms)-1 ) {
echo " | " ;
}
$i++;
}

//list everything
if ($tax_terms) {
  foreach ($tax_terms  as $tax_term) {
    $args=array(
      'post_type' => $post_type,
      "$tax" => $tax_term->slug,
      'post_status' => 'publish',
      'posts_per_page' => -1,
      'caller_get_posts'=> 1
    );

    $my_query = null;
    $my_query = new WP_Query($args);
    if( $my_query->have_posts() ) {
      echo "<h2 class=\"tax_term-heading\" id=\"".$tax_term->slug."\"> $tax_term->name </h2>";
      while ($my_query->have_posts()) : $my_query->the_post(); ?>
        <p><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></p>
        <?php
      endwhile;
      echo "<p><a href=\"#top\">Back to top</a></p>";
    }
    wp_reset_query();
  }
}
?>

About Steven Chu


Hi, I'm Steven! I'm an entrepreneur, photographer and art director in New York. Follow this blog for self expression, fun, and most importantly: looking comfortable, at ease, and amazing in your photos no matter who takes them! I dedicate this to my amazing friends who have let me inadvertently turn all of our hangouts and travel photos into a never ending photoshoot of fun. The proof is in the pudding-- our photos rock. My other projects: I'm the founder of InstaTechie.com, a face-to-face tech concierge service for NYC. Book a techie to walk you through something you want to learn! My work focuses on socially engaged art projects which use technology to create access to resources for communities. Visit Steven Chu Studio (stevenchustudio.com) for branding & design work or Steven Chu (stevenchu.com) for photography projects.

Leave a Reply