Skip to content

Instantly share code, notes, and snippets.

@hearvox
Created September 16, 2019 17:58
Show Gist options
  • Save hearvox/db7d1cc01a4f005f2934308193853481 to your computer and use it in GitHub Desktop.
Save hearvox/db7d1cc01a4f005f2934308193853481 to your computer and use it in GitHub Desktop.
Filter post query results by one one post-meta value; sort results by another post-meta value.
<?php
/**
* Sort query results by one meta value; filter by another.
* For example, post are 'cities':
* Sort cities with >40K population ('city_pop') by average income ('city_income').
*/
$args = array(
'post_type' => 'cities',
'posts_per_page' => 1000,
'meta_query' => array(
'relation' => 'AND',
array(
'population' => array( // Name this array key to use in 'onderby' below in ).
'key' => 'city_pop', // Sort results by values with this meta key.
'compare' => 'EXIST'
)
),
array(
'key' => 'city_income', // Filter results by values in this meta_key.
'value' => 40000, // Limits resutls to >40K. Uses 'compare' below.
'type' => 'numeric',
'compare' => '>',
)
),
'orderby' => array( 'population' => 'DESC', 'title' => 'ASC' ), // Named array key from above.
);
$query_sort_limit = new WP_Query( $args );
// Make array of Publications data.
foreach ( $query_sort_limit->posts as $post ) {
// Do stuff.
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment