Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

Assume a post is categorized in "Fruit" and tagged with "Apple".
The following code shows posts with category "Fruit" AND tag "Apple"

$args = array(  
    'tag__in' => $tag_in,  
    'category__in' => $category_in,  
);
query_posts($args);

How to show all posts which are from either category "Fruit" OR tag "Apple"?

share|improve this question
add comment

1 Answer

up vote 3 down vote accepted

You can achieve that with a tax_query with OR relation. See the Taxonomy Parameters section for WP_Query in Codex for the different tax query parameters.

$args = array(
    'tax_query' => array(
        'relation' => 'OR',
        array(
            'taxonomy' => 'category',
            'field' => 'slug',
            'terms' => array( 'fruit' )
        ),
        array(
            'taxonomy' => 'post_tag',
            'field' => 'slug',
            'terms' => array( 'apple' )
        )
    )
);
$query = new WP_Query( $args );

In the above example we've created a new WP_Query instance instead of using query_posts(). This is the correct method if this is an additional query aside from the page's main query.

If this is the main query, see the pre_get_posts action for how to add these parameters to the main query before the query is sent to the database.

Read this for info on the various query methods available and read this for info on why you shouldn't use query_posts().

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.