/doctors/
is a post type archive, so we can check if that query is being run in the pre_get_posts
action via the conditional tag is_post_type_archive( 'doctors' )
and modify those queries accordingly.
WordPress passes the query object to the function by reference ( $query
in this example ), so we can modify the query vars via the set
method of the query object. This code would go in your theme’s functions.php
file:
function wpa_doctor_gender( $query ) {
// if this is the main query on the doctors post type archive
if ( $query->is_post_type_archive( 'doctors' )
&& $query->is_main_query() ) {
// set query vars for all doctors queries
$query->set( 'meta_key', 'last_name' );
$query->set( 'orderby', 'meta_value' );
$query->set( 'order', 'ASC' );
// set meta_query if gender is female
if ( isset( $_GET['gender'] )
&& 'female' == $_GET['gender'] ){
$meta_query = array(
array(
'key' => 'gender',
'value' => $_GET['gender'],
'compare' => 'IN'
)
)
$query->set( 'meta_query', $meta_query );
}
}
}
add_action( 'pre_get_posts', 'wpa_doctor_gender' );
Now in the template, we can get rid of all the custom query code and loop, and just run the vanilla loop to output posts:
while( have_posts() ) {
the_post();
the_title();
// etc..
}