Skip to content

Instantly share code, notes, and snippets.

@jamesmorrison
Created January 10, 2018 11:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jamesmorrison/6501a1193cb76cd0c9f9d5c4c3fe5d26 to your computer and use it in GitHub Desktop.
Save jamesmorrison/6501a1193cb76cd0c9f9d5c4c3fe5d26 to your computer and use it in GitHub Desktop.
Custom query with conditional taxonomy args
<?php
// Set up default query
$locations_query_args = [
'post_type' => 'locations',
'post_status' => 'publish',
'posts_per_page' => 500,
];
// Add the search query if set ($town_city_selected)
if ( false !== $town_city_selected ) {
$locations_query_args['s'] = esc_attr( $town_city_selected );
}
// Set the nearest station if set
if ( false !== $nearest_station_selected ) {
$locations_query_args['tax_query'][] = [
'taxonomy' => 'nearest_station',
'field' => 'term_id',
'terms' => esc_attr( $nearest_station_selected ),
];
}
// Set the theme(s) if set
if ( false !== $themes_selected ) {
$locations_query_args['tax_query'][] = [
'taxonomy' => 'themes',
'field' => 'term_id',
'terms' => $themes_selected,
];
}
// If BOTH taxonomies (nearest station and theme(s)) have a value then this is a relation = AND query (we need to deal with both)
if ( false !== $nearest_station_selected && false !== $themes_selected ) {
$locations_query_args['tax_query']['relation'] = 'AND';
}
// Process query
$locations_query = new WP_Query( $locations_query_args );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment