Retrieve posts from 2 categories (2 posts)

  1. Alin Ionut
    Posted 2 years ago #

    Is it possible to retrieve posts that have category A and B selected as categories? For example:

    post 1 - cat A,B
    post 2 - cat A,B,C
    post 3 - cat B,C,D
    post 4 - cat A,B
    post 5 - cat B,D

    and I want to retrieve just posts 1 and 4.

  2. vtxyzzy
    Posted 2 years ago #

    If you know all the categories you want to exclude, I think you can use a tax_query like this:

    $args = array(
    	'post_type' => 'post',
    	'tax_query' => array(
    		'relation' => 'AND',
    			'taxonomy' => 'category',
    			'field' => 'slug',
    			'terms' => array( 'a', 'b' ),
    			'operator' => 'AND'
    			'taxonomy' => 'category',
    			'field' => 'slug',
    			'terms' => array( 'c', 'd' ),
    			'operator' => 'NOT IN'
    $query = new WP_Query( $args );

    If you don't know all the categories up front, you could use a separate query to find all category slugs, eliminate the 'a' and 'b', and use an array of the rest in the second part of the tax_query.

Topic Closed

This topic has been closed to new replies.

About this Topic