[wp-hackers] advanced taxonomy queries

Chip Bennett chip at chipbennett.net
Fri Dec 21 04:28:49 UTC 2012


Pass the 'foo' and 'bar' category $id values as an array to the
`category__in` parameter:

$args = array( 'category__in' => array( 1, 2 ) );

$custom_query = new WP_Query( $args );

p.s. avoid query_posts() here. Use a new instance of WP_Query() if you're
creating a secondary loop, or filter the main $query via pre_get_posts, if
you're modifying the main query.

Chip


On Thu, Dec 20, 2012 at 11:22 PM, Ian Dunn <ian at iandunn.name> wrote:

> I haven't tested this, but you might want to give it a shot:
>
> $fooBarQuery[ 'tax_query' ] = array(
>
>     array(
>         'taxonomy'    => 'category',
>         'terms'        => 'foo',
>
>         'field'        => 'slug',
>     ),
>     array(
>         'taxonomy'    => 'category',
>         'terms'        => 'bar',
>
>         'field'        => 'slug',
>     ),
>     'relation'        => 'OR'
> );
> $fooBarPosts = get_posts( $fooBarQuery );
>
> There may be a more elegant way to do it, but I'm not seeing it from a
> quick glance at the Codex. If not, then you'd need to use
> $wpdb->get_results() with a custom query.
>
> Also, check out http://wordpress.**stackexchange.com/questions/**
> 1753/when-should-you-use-wp-**query-vs-query-posts-vs-get-**posts<http://wordpress.stackexchange.com/questions/1753/when-should-you-use-wp-query-vs-query-posts-vs-get-posts>with regards to using query_posts().
>
>
>
>
> On 12/20/2012 10:04 PM, Haluk Karamete wrote:
>
>> In this query, we get the posts in the foo cat OR the bar cat
>>
>> $myquery['tax_query'] = array(
>>      array(
>>          'taxonomy' =>  'category',
>>          'terms' =>  array('foo', 'bar'),
>>          'field' =>  'slug',
>>      ),
>> );
>> query_posts($myquery);
>>
>> how do we change in the above snippet it so that we get the posts that
>> are in both categpories? That is both in the foo cat *AND* in the bar
>> cat?
>> ______________________________**_________________
>> wp-hackers mailing list
>> wp-hackers at lists.automattic.**com <wp-hackers at lists.automattic.com>
>> http://lists.automattic.com/**mailman/listinfo/wp-hackers<http://lists.automattic.com/mailman/listinfo/wp-hackers>
>>
> ______________________________**_________________
> wp-hackers mailing list
> wp-hackers at lists.automattic.**com <wp-hackers at lists.automattic.com>
> http://lists.automattic.com/**mailman/listinfo/wp-hackers<http://lists.automattic.com/mailman/listinfo/wp-hackers>
>


More information about the wp-hackers mailing list