WordPress Query: sort by meta_key && compare by meta_key

I needed to run a query that pulled all posts that had a specific value ( or values ), and sort them by another meta key.

The custom fields (meta keys) I am using in this example are:
  • Age
  • Favorite_Color
The Requirements:
  • Sort by “Age”, showing the youngest first.
  • Show all posts that have Favorite_Color == to $favorite_color.
    • Note: $favorite_color can be an array that has multiple colors.
Here is the query I found that works!
	$args = array(
			'post_type' => 'custom_post_slug', // or 'posts' if you don't have one.
			'posts_per_page' => -1, // get ALL posts
			'order_by' => 'title',
			'title_li' => '',
			'order' => 'ASC',
			'meta_key' => 'age',
 			'orderby' => 'meta_value_num', // sort by age.  use 'meta_value' if the values aren't just numeric.
			'meta_query' => array(
					'key' => 'favorite_color', 
					'value' => $favorite_color,
					'compare' => 'IN'	// because $favorite_color might be an array.  This will look IN the array.
$results = get_posts($args);

Hopefully this is helpful!

Leave a Reply

Your email address will not be published. Required fields are marked *