Tag Archives: query

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!

Query Multiple Meta Values in WordPress and use CONCAT()

I needed to pull two specific meta values for each custom post type into an array. I wanted them to be combined as one reference, and I wanted to use only one query.

With the help of multiple online sources, I was able to figure it out.
function get_your_meta($key1 = '', $key2 = '', $type = 'post', $status = 'publish') {
    global $wpdb;
    if(empty($key1) || (empty($key2))) {
    $r = $wpdb->get_results( $wpdb->prepare(
			CONCAT(pm.meta_value, ' ', pm2.meta_value) AS `name`,
		FROM {$wpdb->posts} p
		INNER JOIN {$wpdb->postmeta} pm
			ON p.ID = pm.post_id
        INNER JOIN {$wpdb->postmeta} pm2
			ON p.ID = pm2.post_id
		WHERE pm.meta_key = '%s'
		AND pm2.meta_key = '%s'
        AND p.post_status = '%s' 
        AND p.post_type = '%s'
    $key1, $key2, $status, $type) );
    return $r;
Simply call the function using
$arr = get_your_meta("meta_key_1", "meta_key_2", "post"); 
Of course, if you’re using a custom post type, change as such.