I need to list posts on tag archives, grouped by the category they are in, with the category name above the group of posts. So the output would look something like this:
<h1>'Brown' Tag</h1>
<h2>'Dogs' Category</h2>
<h3>Brown Labrador</h3>
<p>bla bla bla</p>
<h3>German Shepherd</h3>
<p>yada yada yada</p>
<h2>'Cats' Category</h2>
<h3>Siamese</h3>
<p>meow meow</p>
<h3>Havana Brown</h3>
<p>miou miou</p>
I would have thought that was a fairly simple thing to do, but for the life of me, I can't seem to figure it out! I've tried using has_tag, in_category, query_post, and multiple variations thereof, to no avail. I've scoured the Codex, the forum, and am unable to find an answer, although there are many posts that *appear* similar, they are missing the bit of having the Category title above the post grouping.
The closest I've come is using this code on archive.php:
<?php
if (is_tag()) {
while (have_posts()) : the_post();
if (in_category('117')) {
echo "<h2>Dogs</h2>";
} elseif (in_category('116')) {
echo "<h2>Cats</h2>";
} ?>
<h3><?php the_title(); ?></h3>
<?php the_excerpt(); ?>
<?php endwhile; ?>
<?php } else {
//Something else
} ?>
However, the result adds the Category name before every post in each respective group.
<h1>'Brown' Tag</h1>
<h2>'Dogs' Category</h2>
<h3>Brown Labrador</h3>
<p>bla bla bla</p>
<h2>'Dogs' Category</h2>
<h3>German Shepherd</h3>
<p>yada yada yada</p>
<h2>'Cats' Category</h2>
<h3>Siamese</h3>
<p>meow meow</p>
<h2>'Cats' Category</h2>
<h3>Havana Brown</h3>
<p>miou miou</p>
Do you have any idea how I can fix this? Thank you