With WordPress now able to use custom post types, I have asked on forums if anyone new how to filter by more than one taxonomy. I originally tried using
query_posts('cat=6,5')
and other similar commands but have no luck.
To resolve this I came up with the following solution:
First I create two custom fields on the page which I named taxonomy1 and taxonomy2.
I then added the following code:
<?php
$taxonomy1 = get_post_meta($post->ID, "taxonomy1");
$taxonomy2 = get_post_meta($post->ID, "taxonomy2");
//this is an sql query to find all posts containing two taxonomies
$sql_query = "SELECT * FROM (
SELECT wp_posts.ID FROM `wp_posts`
JOIN wp_term_relationships ON wp_posts.ID=wp_term_relationships.object_id
JOIN wp_terms ON wp_term_relationships.term_taxonomy_id=wp_terms.term_id
WHERE slug = '".$taxonomy1[0]."'
UNION ALL
SELECT wp_posts.ID FROM `wp_posts`
JOIN wp_term_relationships ON wp_posts.ID=wp_term_relationships.object_id
JOIN wp_terms ON wp_term_relationships.term_taxonomy_id=wp_terms.term_id
WHERE post_type = 'tiles' AND slug = '".$taxonomy2[0]."'
) AS results
GROUP BY results.id HAVING COUNT(*) = 2";
$newresults = $wpdb->get_results($sql_query);
$ArrayOfIDs = array();
foreach($newresults as $newresult){
array_push($ArrayOfIDs, $newresult->ID);
}
query_posts(array('posts_per_page'=>'900','post_type' => 'tiles','post__in' => $ArrayOfIDs));
?>
The idea behind this code is that the mysql query returns the post IDs of the posts that correspond to the two taxonomy filters and then the foreach loop pushes those into an array of IDs ($ArrayOfIDs) which is then used in the query_post function.
Feedback would be much appreciated on other ways that I could have resolved this issue or also how I could improve this code.
October 7th, 2010



Home


















