So on this Custom Post Type list page there is a list of Properties.
I have a custom search feature where they can search for Properties with certain Taxonomy Terms - but they can also search for Multiple Taxonomy Terms.
Question:
If someone selects 2 terms then the only Properties that should display in the list are Properties with term_one
AND
term_two
So I tried this below:
$required_features_slugs = array();
if( isset ( $_GET['features'] ) ) {
$features_slugs = $_GET['features'];
}
$feature = get_terms('features');
$tmp_required = $required_features_slugs;
$property = array(
'post_type' => 'properties',
'paged' => $paged,
'tax_query' => array(
array(
'taxonomy' => 'features',
'field' => 'slug',
'terms' => $tmp_required,
'operator' => 'AND',
)
),
);
The URL looks like this:
features%5B%5D=accredited-landlord&features%5B%5D=cellarbasement
Now because these two Features are selected it should only return one Property because there is only one Property with term_one
AND
term_two
together
However I don't get this result instead I get 4 Properties because there are 4 Properties. 3 with term_one
and 1 with term_two
.
What I want to happen is for 1 Property to be returned because there is only one Property with term_once
AND
term_two
together.
Is there something wrong that I am doing in the Query?
Edit: Updated PHP
file
$required_features_slugs = array();
if( isset ( $_GET['features'] ) ) {
$required_features_slugs = $_GET['features'];
}
$all_features = get_terms('features');
if( ! empty( $required_features_slugs ) ) {
foreach ( $all_features as $feature ) {
$tmp_required = $required_features_slugs;
if( ! in_array($feature->slug, $required_features_slugs) ) {
array_push( $tmp_required, $feature->slug );
}
$property = array(
'post_type' => 'properties',
'paged' => $paged,
'tax_query' => array(
'taxonomy' => 'features',
'field' => 'slug',
'terms' => $tmp_required,
'operator' => 'AND',
),
);
}
}
Edit #2:
So here is the var_dump
to the Query:
array(3) { ["post_type"]=> string(10) "properties" ["paged"]=> int(1) ["tax_query"]=> array(4) { ["taxonomy"]=> string(8) "features" ["field"]=> string(4) "slug" ["terms"]=> array(2) { [0]=> string(19) "accredited-landlord" [1]=> string(14) "cellarbasement" } ["operator"]=> string(3) "AND" } }
And here is the var_dump
to the terms:
array(2) { [0]=> string(19) "accredited-landlord" [1]=> string(14) "cellarbasement" }
$required_features_slugs
and$tmp_required
are currently empty arrays and$features_slugs
and$feature
are never used.features
in$_GET
should have brackets on end to behave as array, for exampleexample.com/?features[]=10&features[]=20...
[]
there in Unicode%5B%5D
is the[]
in Unicode