WordPress - producing a list of posts filtered by tag and then category
Solution 1
Right, I have finally found a relatively simple solution to this.
There's a bug in WordPress preventing a query of both category and tags working, so query_posts('cat=2&tag=bread');
wouldn't work, but a way around this is query_posts('cat=2&tag=bread+tag=bread');
which magically works.
In a tag.php template, I wanted it to pick up the tag from that archive, so I had to do this:
<?php query_posts('cat=12&tag='.$_GET['tag'].'+'.$_GET['tag']); ?>
which works perfectly.
Solution 2
Try this code:
query_posts('tag=selected_tag');
while (have_posts()) : the_post();
foreach((get_the_category()) as $category)
{
if ($category->cat_name == 'selected_category')
{
// output any needed post info, for example:
echo the_title();
}
}
endwhile;
Laura Kalbag
Updated on June 23, 2022Comments
-
Laura Kalbag almost 2 years
I'm trying to make a WordPress site that has six lists on a page, each list showing posts from a different category. Simple.
But then, if a user selects a tag, taking them to that tag archive page, I want them to still see the six-list template, but all the posts within each category are also filtered by the tag. So lists of posts are filtered first by tag, and then by category.
As far as I can tell, there is no way of doing this using query_posts or anything, it needs more advanced use of the database, but I have no idea how to do this! I think that there's a similar question on here, but because I know very little PHP and no MySQL, I can't make sense of the answers!
-
Laura Kalbag almost 15 yearsUnfortunately this query will override a category, and you cannot use it to filter by category within a tag, it will only show all the posts with that category and all the posts within that tag.
-
Evan Meagher almost 15 yearsYou could initially call get_query to get an array of posts filtered by tag. Then iterate over it and manually allocate posts into an array for each of the six categories.
-
Laura Kalbag almost 15 yearsThis sounds like the perfect thing, but I'm no PHPer, so I've got no idea how to do it!
-
Wiseman almost 15 yearsYou've replaced 'selected_tag' and 'selected_category' with your own values, haven't you? 8) It may be useful to place this code in wordpress template and make 6 of them for each page.
-
Wiseman almost 15 yearsCan you please post your whole template text? I suppose there might be a little mistake somewhere.
-
Scott Gottreu almost 15 yearsI copied the code into one of my themes. I'm guessing there is a misspelling in your tag or category in the code. Also I believe that the tags and categories are case-sensitive.