Support » Fixing WordPress » Retrieve posts from 2 categories

  • 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.

Viewing 1 replies (of 1 total)
  • 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',
    		array(
    			'taxonomy' => 'category',
    			'field' => 'slug',
    			'terms' => array( 'a', 'b' ),
    			'operator' => 'AND'
    		),
    		array(
    			'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.

Viewing 1 replies (of 1 total)
  • The topic ‘Retrieve posts from 2 categories’ is closed to new replies.