I have a bunch of posts that each have multiple tags, and I’m trying to find a way to output all of them on a single page, organized under an alphabetical listing of their respective tags. E.g. if Post1 has the tags A, B and D and Post2 has the tags A, C and D, the output would look like this:
Tag A
Post1
Post2Tag B
Post 1Tag C
Post2Tag D
Post1
Post2
EDIT: I’ve gotten it working with categories, but I’d still love to have it work with tags instead. (All of the excluded IDs are because I’m technically using categories for other organization.) The functional code is:
<?php $cat_args = array(
'orderby' => 'title',
'order' => 'ASC',
'exclude' => '26,27,32,52,36,31,42,38,41'
);
$categories = get_categories($cat_args);
foreach ($categories as $category)
{
$catID = $category->term_id;
$catName = $category->name;
echo '<strong>'.$catName.'</strong>';
global $post; // required
$pArgs = array('category' => $catID,'post_type' => 'shows','orderby' => 'title', 'order' => 'ASC');
$custom_posts = get_posts($pArgs);
foreach($custom_posts as $post) : setup_postdata($post); ?>
<div class="show">
<a href="<?php the_permalink(); ?>">
<?php the_post_thumbnail("show"); ?>
<h3 class="center"><?php the_title(); ?></h3>
</a>
</div>
<?php endforeach; ?>
<?php } ?>
(Untested) but should works with any taxonomy including the ‘tag’ taxonomy (
post_tag
). The following example uses the taxonomy with name ‘my-taxonomy’.Here’s the final code I used with a custom taxonomy (edited based on Stephen’s answer above so it actually works – I was still just querying categories with my old code):
First you’ll need to get all the tags you’ve used, then pass them to WP_Query and get all the posts.
Not tried this code, but should give you an idea. Put the additional checks wherever needed.