Building conditional WP_Query args based on variables

I have not seen this documented anywhere other than this thread I found on the WordPress Stackexchange: http://wordpress.stackexchange.com/questions/107471/how-to-use-tax-query-to-apply-both-terms-or-one-if-one-is-empty?codekitCB=403616342.846423

The following is my implementation of it on the NN Occ Health Job Matrix theme in the file ‘content/.php:
($body_demand_one, $body_demand_two are variables set from query parameters passed from the url.)

$args = array();
if ( $body_demand_one || $body_demand_two ) {
	//echo 'We do add to the archive query!<br/>';
	$args['tax_query'] = array();
	if ( $body_demand_one ) {
		$args['tax_query'][] = array(
			'taxonomy' => 'body_demands',
			'field' => 'slug',
			'terms' => $body_demand_one
		);
	}
	if ( $body_demand_two ) {
		$args['tax_query'][] = array(
			'taxonomy' => 'body_demands',
			'field' => 'slug',
			'terms' => $body_demand_two
		);
	}
}
if ( $work_attribute && $body_demand ) $args['tax_query']['relation'] = 'AND';
$args = array_merge(
	$wp_query->query_vars,
	$args
);
query_posts( $args );

Revisions

Tags:

No comments yet.

Leave a Reply