both "AND" and "OR" filters

Hello! I’m trying to create in PHP the option to filter case studies by several filters. I’ve used the “AND” function, so that “filter one + filter two + filter three” will filter the case studies down to any that match that criteria.

Where I’m stuck is I can’t figure out how to make it so that if one of the filters is left blank, or if only one filter is selected, it will filter by just the one or two categories instead of all three. My link is http://bit.ly/1X7kgeJ and my code is

[php] <?php
$args=array(‘post_type’ => ‘case_studies’ ,‘orderby’ => ‘ID’ ,‘order’ => ‘ASC’ , ‘posts_per_page’ => 12,‘paged’=>get_query_var(‘paged’));

				   if(isset($_POST['submit']) && ($_POST['case_studie_category'] or $_POST['case_studie_theme'] or $_POST['case_studie_sector'])){
					     $case_studie_category=$_POST['case_studie_category'];
						 $case_studie_theme=$_POST['case_studie_theme'];
						  $case_studie_sector=$_POST['case_studie_sector'];
					$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
					$args = array(
							'post_type' => array('case_studies'),
							'paged' => $paged,
							 'posts_per_page' => 12,
							'tax_query' => array(
								  'relation' => ‘AND’,
							   array(
								'taxonomy' => 'case_studie_category',
								'terms' => $case_studie_category,
								'field' => 'slug'
							   ),
							   array(
								'taxonomy' => 'case_studie_theme',
								'terms' => $case_studie_theme,
								'field' => 'slug'
							   ),
								 array(
								'taxonomy' => 'case_studie_sector',
								'terms' => $case_studie_sector,
								'field' => 'slug'
							   ),
							)
						);
					}[/php]

many thanks!

Well, I would “build” the filter before you place it into the query. Assuming you are placing your filtering into a
query, you would be using WHERE something=something AND something2=something2, etc…

So, you create a temporary variable like " $filters " and set it to “”, then you check your optional input filters and
add them to the $filters variable. Just loosely like:
$filters = “”;
if(cond1) $filters .= " something1=‘something’ "
if(cond2) $filters .= " AND something2=‘something’ "
etc…
$query = "SELECT * WHERE " . $filters;
If the database starts with a WHERE clause that has AND as it’s first part, it just skips over it and should not be
an issue. You just add the filters into the WHERE clause and you should be all set.

Not sure if that is what you need, but, hope that helps…

Sponsor our Newsletter | Privacy Policy | Terms of Service