List all posts in Custom Post Type but group dynamically by Custom Taxonomies

I have a custom post type named “Resources” which has a Taxonomy named “Types.”
I have it manually pulling each term which isn’t the most elegant solution and every time there is a new term added, I have to add it in manually.

I need a way for the Terms to populate with the posts associated listed below. I have a custom loop for displaying each post (pulling in custom fields) so I need to have control over what is displayed for each post.

Read More

Is there an easy way to go about this? Thanks.

Related posts

Leave a Reply

2 comments

  1. Try this piece of code for page template. I’ve used it on one of my projects. It outputs taxonomy term one by one with list of all posts with this term. (Just replace YOUR_TAXONOMY_SLUG to yours)

    <div id="content">
    <h2 class="entry-title"><?php the_title(); ?></h2>
        <div id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
        $mytaxonomy = get_terms('YOUR_TAXONOMY_SLUG', array("fields" => "names"));
        <?php for ( $myterm = 0; $myterm < count($mytaxonomy); $myterm++) { ?>
            <h3><?php echo $mytaxonomy[$myterm]; ?>:</h3>
            <ul class="taxonomy_group">
            <?php $loop = new WP_Query(array('YOUR_TAXONOMY_SLUG' => $mytaxonomy[$myterm]));
                while ( $loop->have_posts() ) : $loop->the_post(); ?>
                    <li><a href="<?php the_permalink(); ?>"><?php the_title();?></a></li>
                <?php endwhile; ?>  
            </ul>
        <?php } ?>
        </div><!-- #post-## -->
    </div><!-- #content -->
    
  2. Take note, this loop will only work if the category is a single word. WP_Query requires the category SLUG in the loop. If the category name is two words or more separated by nonbreaking space, it will not work (I can verify that because I just tried it). I still haven’t found a way to pull the slug from the given taxonomy term, but I’m working on it.

    ADDENDUM:
    Think I found a way to get around the multiple-word term name problem. Seems to work in my code.

        <div id="content">
    <h2 class="entry-title"><?php the_title(); ?></h2>
        <div id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
    <?php $terms = get_terms('YOUR_TAXONOMY_SLUG');
        $count = count($terms); ?>
    <?php if ($count > 0) {
        foreach ( $terms as $term) { ?>
            <h3><?php echo $term->name; ?></h3>    
            <ul class="taxonomy_group">
            <?php $loop = new WP_Query(array('YOUR_TAXONOMY_SLUG' => $term->slug));
                while ( $loop->have_posts() ) : $loop->the_post(); ?>
                    <li><a href="<?php the_permalink(); ?>"><?php the_title();?></a></li>
                <?php endwhile; ?>  
            </ul>
        <?php }
        } ?>
        </div><!-- #post-## -->
    </div><!-- #content -->
    

    Let me know if this works for anyone else or they see any holes in it.