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”?
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()
.