Query posts by custom post type and custom taxonomy

Pretty sure you can’t match multiple taxonomy terms in a query–Wordpress will only honor the first one and ignore the rest.

Apparently, this is scheduled to be fixed in 3.1.

In the meantime, there is a plugin that’ll fix you right up: http://scribu.net/wordpress/query-multiple-taxonomies

EDIT:
If you want a non-plugin solution, let me know. I’ve got one I use.

EDIT:
Here is the quick and dirty non-plugin way. Drop this code into your functions.php file.

function wpse_5057_match_multiple_taxonomy_terms($where_clause, $wp_query) {

    // If the query obj exists
    if (isset($wp_query->query)) {

        $multi_query = $wp_query->query;

        if (is_array($multi_query) && isset($multi_query['multiple_terms'])) {

            global $wpdb;
            $arr_terms = $multi_query['multiple_terms'];

            foreach($arr_terms as $key => $value) {

                $sql = "AND $wpdb->posts.ID IN(
                    SELECT tr.object_id
                    FROM $wpdb->term_relationships AS tr
                    INNER JOIN $wpdb->term_taxonomy AS tt ON tr.term_taxonomy_id = tt.term_taxonomy_id
                    INNER JOIN $wpdb->terms AS t ON tt.term_id = t.term_id
                    WHERE tt.taxonomy='%s' AND t.slug='%s')";

                $where_clause .= $wpdb->prepare($sql, $key, $value); // add to the where

            }
        }

    }

    return $where_clause; // return the filtered where

}
add_action('posts_where','wpse_5057_match_multiple_taxonomy_terms',10,2); // Hook this to posts_where

Now, when you run a query, add a new argument called multiple_terms. This should contain an array where the key is the taxonomy name and the value is the value you’d like to match. Like so:

$args = array(
    'post_type' => 'rv',
    'multiple_terms' => array('manufacturer' => 'Keystone', 'rvtype' => 'fifth-wheel')
);

Works for me. This is modified from an idea I found on another forum or blog, but I can’t find it for the life of me.

Leave a Comment