Setting proper query for multiple custom admin filters

I am adding custom admin filters for my custom post types. I am a bit confused about how to go with the parse_query filter in order to have my posts filtered based on 2 or more filters.

Initially for 1 filter, I can do:

$query->query_vars[‘meta_key’] = ‘city’;
$query->query_vars[‘meta_value’] = $cityId;
$query->query_vars[‘meta_compare’] = ‘=’;

and I will get my filtered results.

I am wondering, if WP would accept more meta_keys/values for the query_vars…

I am trying to set a meta_query and below is what I have done – but it doesn’t work.

add_filter( ‘parse_query’, ‘wpr_manager_filter’ );
function wpr_manager_filter($query) {
global $page;
$current_page = isset( $_GET[‘post_type’] ) ? $_GET[‘post_type’] : ”;

if ( is_admin()
&& ‘properties’ == $current_page
&& ‘edit.php’ == $page
)
{
$metaQuery = array();
if (isset( $_GET[‘city-filter’] ) && $_GET[‘city-filter’] != ‘-1’)
{
$cityId = (int)$_GET[‘city-filter’];
$metaQuery[‘relation’] = ‘AND’;
$metaQuery[] = array(
‘meta_key’ => ‘city’,
‘meta_value’ => $cityId,
‘meta_compare’ => ‘=’
);

// $query->query_vars[‘meta_key’] = ‘city’;
// $query->query_vars[‘meta_value’] = $cityId;
// $query->query_vars[‘meta_compare’] = ‘=’;
}
if (isset( $_GET[‘visibility-filter’] ) && $_GET[‘visibility-filter’] != ‘-1’)
{
$visibility = (int)$_GET[‘visibility-filter’];
$metaQuery[2] = array(
‘meta_key’ => ‘visibility’,
‘meta_value’ => $visibility,
‘meta_compare’ => ‘=’
);
}
$query->meta_query = $metaQuery;
}
}

It has been a long day, and I have just start getting more familiar with deeper WP concepts, so any kind of help that will push me forward and will explain me what I am doing wrong it would be greatly appreciated.

Read more here:: Setting proper query for multiple custom admin filters

Leave a Reply

Your email address will not be published. Required fields are marked *