mw1197 on "Linking to Multiple Categories"

August 21, 2011

Thanks so much, this did exactly what I needed.

Quick explanation for anyone who might need this, since I ended up making a few changes:

For some reason using a single string in the query wouldn’t work and would display any post in the category listed first in the url. I wasn’t able to fix this, despite the string being correct. Instead I ended up passing two variables in the url:

http://yoursite.com/yourpage/?my_cat=1&my_cat2=2

And using two strings:

query_posts( array('category__and' => array ($my_category,$my_category2) ));

However I ended up wanting to using the category name instead of id, which can be done using code from this post:

http://ottopress.com/2010/wordpress-3-1-advanced-taxonomy-queries/

Using that, here’s the final code that goes in your custom page template:

<?php
$my_category = $_GET['my_cat'];
$my_category2 = $_GET['my_cat2'];

$myquery['tax_query'] = array(
	array(
		'taxonomy' => 'category',
		'terms' => array($my_category),
		'field' => 'slug',
	),
	array(
		'taxonomy' => 'category',
		'terms' => array($my_category2),
		'field' => 'slug',
	),
);
query_posts($myquery);
 ?>
<?php while ( have_posts() ) : the_post(); ?>

<!-- Do stuff... -->

<?php endwhile; ?>

And you just use the category name in the link instead of id:

'http://yoursite.com/yourpage/?my_cat=first&my_cat2=second'

Thanks again for the help, really appreciate it!

Leave a Comment

Previous post:

Next post: