How to group posts according to tag (WordPress)

I would like to list all post on one page, but I would like the posts to be grouped by tags. Is this possible in WordPress?

Basically this way:

Read More

Bikes:

Posted 2/8/2011
Some post title 1
Tag bikes

Posted 1/8/2011
Some post title 2
Tag bikes


Cars:

Posted 5/8/2011
Some post title 5
Tag cars

Posted 29/7/2011
Some post title 6
Tag cars


Boats:

Posted 30/7/2011
Some post title 4
Tag boats


Is this possible to do? It should dynamic so that I can create new tags from WP admin and they would show up automatically.

Related posts

Leave a Reply

2 comments

  1. Loop though the tags using get_tags() and use get_posts with the ‘tag_in’ argument.

    ie.

                    <?php foreach(get_tags() as $term){ ?>
    
                        <?php $posts = get_posts( array( 'posts_per_page' => -1, 'post_type' => 'project', 'tag__in' => $term->term_id ) ); ?>
    
                        <?php if($posts) : ?>
    
                            <h3><?php echo $term->name; ?></h3>
    
                            <?php foreach($posts as $post) : ?>
                                    <?php setup_postdata($post); ?>
    
                                    <div class="item col-sm-12">
                                        <a href="<?php the_permalink(); ?>">
                                           <?php the_title(); ?>  <br/> 
    
                                        </a>
                                        <a class="button" href="<?php the_permalink() ?>">Read More</a>
                                    </div>
    
                             <?php endforeach ?>
    
                             <?php wp_reset_postdata(); ?>
    
                        <?php endif; ?>
    
                    <?php } ?>
    
  2. It depends. Are you trying to show posts for all tags, or just listing all posts by specific tags you’ve already decided on?

    If you know the tags you want to display, here is how you would list posts by tag.

    <?php $bikePosts = new WP_Query('tag=bikes');
    while ($bikePosts->have_posts()) : $bikePosts->the_post(); ?>
    
    <h2>Bikes:</h2>
    <p>Posted <?php the_time('j/m/Y'); ?> <?php the_title(); ?>
    
    <?php endwhile; 
    //reset post data for next tag
    wp_reset_postdata();
    ?>
    

    More info: http://codex.wordpress.org/Class_Reference/WP_Query#Tag_Parameters