I have a loop for getting all posts grouped by category for a given tag (see code below). I need to turn it around and do the exact same thing but by tags for a given category.
In the code sample I am getting all posts tagged “torrington” and then doing a loop to display them grouped by category with an H2 of the category (e.g. “restaurants”).
So in the reverse, I need to get all items category “restaurants” and then group them by tag (e.g. “torrington”, “danbury” etc.).
<?php
// get all the categories from the database
$cats = get_categories();
// loop through the categries
foreach ($cats as $cat) {
// setup the cateogory ID
$cat_id= $cat->term_id;
// create a custom wordpress query
query_posts("cat=$cat_id&tag=torrington&post_per_page=100");
// start the wordpress loop!
if (have_posts()) :
// Make a header for the category
echo '<h2 class="cat-title">'.$cat->name.'</h2>';
while (have_posts()) :
the_post(); ?>
<?php // create our link now that the post is setup ?>
<div class="listing">
<a href="<?php the_permalink();?>"><?php the_title(); ?></a>
<?php the_content(); ?>
</div>
<?php //echo '<hr/>'; ?>
<?php endwhile; endif; // done our wordpress loop. Will start again for each category ?>
<?php } // done the foreach statement ?>
EDIT: I’ve gotten this far, but the query_posts statement seems to return nothing:
<?php
// get all the categories from the database
$tags = get_tags();
// loop through the categries
foreach ($tags as $tag) {
echo($tag->name);
// setup the cateogory ID
$tag_id = $tag->term_id;
echo($tag_id);
// create a custom wordpress query
query_posts("tag_id=$tag_id&cat=eats&post_per_page=100");
// start the wordpress loop!
if (have_posts()) :
echo('posts');
// Make a header for the category
echo '<h2 class="cat-title">'.$tag->name.'</h2>';
while (have_posts()) :
the_post(); ?>
<?php // create our link now that the post is setup ?>
<div class="listing">
<a href="<?php the_permalink();?>"><?php the_title(); ?></a>
<?php the_content(); ?>
</div>
<?php //echo '<hr/>'; ?>
<?php endwhile; endif; // done our wordpress loop. Will start again for each category ?>
<?php } // done the foreach statement ?>
Got it. It was simple change of
tag_id=$tag_idnottag=$tag_id.Code above updated. Relevant line is
query_posts("tag_id=$tag_id&cat=eats&post_per_page=100");