I have a custom post type ‘Property’ which my users need to be able to search by meta data.
I have 3 search functions – 2 on the frontend 1 in the admin area – 2 of which are running as expected and one which doesn’t seem to be filtering results at all.
I think there may be a problem with either my definition or usage of custom query_vars.
In my functions.php I have the following:
function add_query_vars($public_query_vars) {
$public_query_vars[] = 'bedrooms';
$public_query_vars[] = 'type';
$public_query_vars[] = 'location';
return $public_query_vars;
}
add_filter('query_vars', 'add_query_vars');
function meta_search_query($query) {
$query_args_code = array(
'posts_per_page' => 5,
'post_type' => 'nc_property',
'meta_key' => 'nc_code',
'meta_value' => $query->query_vars['s'],
'meta_compare' => 'LIKE'
);
$query_args_meta = array(
'posts_per_page' => -1,
'post_type' => 'nc_property',
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'nc_bedrooms',
'value' => $query->query_vars['bedrooms'],
'compare' => 'LIKE'
),
array(
'key' => 'nc_type',
'value' => $query->query_vars['type'],
'compare' => 'LIKE'
),
array(
'key' => 'nc_location',
'value' => $query->query_vars['location'],
'compare' => 'LIKE'
)
)
);
if (is_admin() && $query->is_search ) {
query_posts($query_args_code);
} elseif (!is_admin() && $query->is_search ) {
if ($_REQUEST["which_form"] == 'meta_form') {
query_posts($query_args_meta);
} elseif ($_REQUEST["which_form"] == 'code_form'){
query_posts($query_args_code);
}
}
}
add_filter( 'pre_get_posts', 'meta_search_query');
Searching by the property code works no problem at all in both the frontend and backend however trying to filter results by the custom query vars – location, type and bedrooms – falls flat everytime.
An example query string which is created is as follows:
/property/?post_type=nc_property&which_form=meta_form&bedrooms=Two&type=Apartment&location=Bahceli
There is one property on the site which matches those details but WordPress returns all results each time.
Have I missed something?
EDIT: It turns out that because my search form for my meta queries was not using an element with 's'
as its name the $query->is_search
condition of my if statement was returning false, meaning my meta_query simply wasn’t being called.
Kudos to fischi for spotting this for me! 😀
In this case, as you mix pretty permalinks with request parameters, I would use the
$_GET
variables in your query.Be sure to use the proper sanitation, depending on your needs, or using a function that checks for whitelisted values of the
$_GET
data.Also check your function of the conditionals – you just alter the query if it is a search request (using
s
as search parameter), or alter theif
statement.