I've created custom post named talent, and created 3 admin filters based on custom fields, i.e., gender, travels from and vaccination.
Here is the code:
add_action('pre_get_posts','talent_filter');
function talent_filter($query) {
if ( ! is_admin() ) {
return;
}
global $pagenow;
if ( 'edit.php' === $pagenow ) {
if ( isset( $_GET['gender'] ) && $_GET['gender'] !== '0' ) {
$query->set('meta_query', array(
'relation' => 'AND',
array(
'key' => 'gender',
'value' => sanitize_text_field($_GET['gender']),
'compare' => '='
),
array(
'key' => 'travels_from',
'value' => sanitize_text_field($_GET['travels_from']),
'compare' => '='
),
array(
'key' => 'vaccination',
'value' => sanitize_text_field($_GET['vaccination']),
'compare' => '='
)) );
}
}
}
The filter code works if I select a value for all the fields except default, however if I try to filter based on only one of the custom fields and keep other 2 filter values to default, it doesn't work