Forums

[resolved] Custom query combining AND / OR category membership? (4 posts)

  1. wintermute77
    Member
    Posted 6 months ago #

    I want to create a custom query that pulls posts that are in category X, and EITHER of categories Y and Z.

    Is there a way to do this using the existing WP_Query params, or would I have to construct my own custom SQL statement?

    As a rough example, I'd like to be able to do something like the below to get posts that are in category 56 and also in either one of categories 12 and 34.

    $featuredPosts = new WP_Query( array(
    	'category__in'	=> array(12, 34),
    	'category__and'	=> array(56)
    ));

    Thanks :)

  2. keesiemeijer
    moderator
    Posted 6 months ago #

    Try it with a tax_query: http://codex.wordpress.org/Function_Reference/WP_Query#Taxonomy_Parameters

    example [untested]:

    $args = array(
    	'tax_query' => array(
    		'relation' => 'AND',
    		array(
    			'taxonomy' => 'category',
    			'field' => 'id',
    			'terms' => array(56)
    		),
    		array(
    			'taxonomy' => 'category',
    			'field' => 'id',
    			'terms' => array( (12, 34 ),
    			'operator' => 'IN'
    		)
    	)
    );
    $query = new WP_Query( $args );
  3. wintermute77
    Member
    Posted 6 months ago #

    Works like a charm. Many thanks.

  4. keesiemeijer
    moderator
    Posted 6 months ago #

    You're welcome. Glad you got it resolved.

Reply

You must log in to post.

About this Topic