• Resolved rubjm9

    (@rubjm9)


    I have been reading the WP_Query Codex looking for a way to loop through all the posts that have the post types ‘video’ OR ‘image’, within a given category. If this wasn’t enough, this category is given by a variable $catslug (I need it to be this way).

    I have only found ways of looping through “image OR video” or “image AND $catslug” or “video AND category”, but what I need is more complex, something like this:

    (post-format-image AND $catslug) OR (post-format-video AND $catslug)

    Is it possible to do a tax_query within a tax_query???
    Something like this

    $args = array(
    	'post_type' => 'post',
    	'tax_query' => array(
    		'relation' => 'OR',
    		'tax_query' => array(
    			'relation' => 'AND',
    			array(
    				'taxonomy' => 'category',
    				'field'    => 'slug',
    				'terms'    => array($catslug)
    			),
    			array(
    				'taxonomy' => 'post_format',
    				'field'    => 'slug',
    				'terms'    => array( 'post-format-image' )
    			)
    		),
    		'tax_query' => array(
    			'relation' => 'AND',
    			array(
    				'taxonomy' => 'category',
    				'field'    => 'slug',
    				'terms'    => array($catslug)
    			),
    			array(
    				'taxonomy' => 'post_format',
    				'field'    => 'slug',
    				'terms'    => array( 'post-format-video' )
    			)
    		)
    	)
    );
    $query = new WP_Query( $args );

    Anyone knows about a workaround or a hack?
    Perhaps I’m just thinking the wrong way (it has been now a whole day developing a theme…)

    Thaaanks!! (:

Viewing 4 replies - 1 through 4 (of 4 total)
  • Have you attempted adding both terms to the array? Something like this:

    $args = array(
    	'post_type' => 'post',
    	'tax_query' => array(
    		'relation' => 'AND',
    		array(
    			'taxonomy' => 'category',
    			'field'    => 'slug',
    			'terms'    => array($catslug)
    		),
    		array(
    			'taxonomy' => 'post_format',
    			'field'    => 'slug',
    			'terms'    => array( 'post-format-image', post-format-video' )
    		)
    	)
    );
    $query = new WP_Query( $args );
    Thread Starter rubjm9

    (@rubjm9)

    Oh!
    That was it… I had tried adding both to the array but I was doing it the wrong way… And ended up over-complicating it!
    This is perfect thanks!!

    Thread Starter rubjm9

    (@rubjm9)

    Just one thing though, in case someone in a future wants to use that piece of code, it is missing an apostrophe before 'post-format-video'
    Thanks again!

    Nice. Glad it worked and thanks for the catch!

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘Query two post types within a category’ is closed to new replies.