Query by one custom field and order by another – WordPress

This is more of an affirmation than a hack. Since the introduction of meta_query in WordPress 3.1, filtering posts by metadata has become significantly less painful. An added benefit is the ability to use meta_key to sort your results without having to filter by meta_value.

The trick is to let meta_query handle the actual filtering and include meta_key to pass a different meta field to the orderby argument.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
$args = array(
	'post_type' => 'put_post_type_here',
	/* use the new meta_query in WP 3.1 for filtering */
	'meta_query' => array(
		array(
			'key' => 'put_filter_meta_key_here',
			'value' => 'put_filter_meta_value_here',
			'compare' => '='
		)
	),
	/* use meta_key for sorting - but don't specify a meta value */
	'meta_key' => 'put_sorting_meta_value_here',
	/* then order by the meta_key above - use meta_value_num for numbers */
	'orderby' => 'meta_value',
	'order' => 'ASC',
 );
query_posts( $args );

Keep in mind:

  • This query only works for sorting by one meta value. Nested sorting will require a SQL query.
  • Dates and times should be in a valid format for chronological sorting (you don’t want the system to misinterpret AM/PM
Post comment as twitter logo facebook logo
Sort: Newest | Oldest